I wrote the following code to read two different text files. One text file is called the “username” text file, while the other is called the “password” text file. I am creating a login program. In order for the user to login successfully, the line number of the username must match that of the password. For some reason however, my LineNumberReader for both files is stuck at zero, which is strange because I put assertions to avoid this and the assertions did not throw an error. I know they are zero because I printed out each reader. It also keeps printing out “Match found” even when I deliberately put in a wrong username-password match. Can anyone figure this out?
public boolean usernamePasswordCheck(String username, String password) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader("src/BioStat/username.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("src/BioStat/password.txt"));
String line;
String line2;
int userLine=0;
int passwordLine=0;
LineNumberReader lnr = new LineNumberReader(new FileReader("src/BioStat/username.txt"));
LineNumberReader lnr2 = new LineNumberReader(new FileReader("src/BioStat/password.txt"));
while((line=br.readLine())!=null){
if(line.equals(username)){
//username is found in username list. There is a match!
//let's get it's line number
userLine = lnr.getLineNumber();
}else{
//username was not found in list, so we should keep reading.
line = br.readLine();
}
}
System.out.println("Userline: "+userLine);
br.close();
while((line2 = br2.readLine())!=null){
if(line2.equals(password)){
//username is found in username list. There is a match!
//let's get it's line number
passwordLine = lnr2.getLineNumber();
}else{
//username was not found in list, so we should keep reading.
line2 = br2.readLine();
}
}
System.out.println("passwordLine: "+passwordLine);
br2.close();
assert(userLine!=0);
assert(passwordLine!=0);
if(userLine==passwordLine){
System.out.println("Match Found");
matchfound = true;
}else{
System.out.println("Username and Password don't match");
}
return matchfound;
}
You aren’t advancing your
LineNumberReaderevery loop. Thewhileloop is taking care of advancing yourBufferedReader.You can actually simplify things and just use the
LineNumberReaderwithout the BufferedReaders because their readLine will give you the text just as aBufferedReaderwill. For example:The call to
readLineon theLineNumberReaderadvances to the next line (and thus will increase the line number as well).