gpt4 book ai didi

java - 为什么 Java 中的 LineNumberReader 总是返回零?

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:20 30 4
gpt4 key购买 nike

我编写了以下代码来读取两个不同的文本文件。一个文本文件称为“用户名”文本文件,而另一个称为“密码”文本文件。我正在创建一个登录程序。为了使用户登录成功,用户名的行号必须与密码的行号匹配。然而,由于某种原因,我的两个文件的 LineNumberReader 都停留在零,这很奇怪,因为我放置了断言来避免这种情况,并且断言没有抛出错误。我知道它们为零,因为我打印出了每个读者。即使我故意输入错误的用户名密码匹配,它也会不断打印出“找到匹配”。有人能弄清楚吗?

    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;
}

最佳答案

您并没有在每个循环中推进您的 LineNumberReaderwhile 循环负责推进您的 BufferedReader

您实际上可以简化事情,只使用 LineNumberReader 而无需使用 BufferedReaders,因为它们的 readLine 会像 BufferedReader 一样为您提供文本。例如:

String line = null;
int userLine=0;
LineNumberReader lnr = new LineNumberReader(new FileReader("src/BioStat/username.txt"));
while((line=lnr.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();
break;
}
}
lnr.close();

LineNumberReader 上的 readLine 的调用前进到下一行(因此也会增加行号)。

关于java - 为什么 Java 中的 LineNumberReader 总是返回零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420958/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com