1

我编写了以下代码来读取两个不同的文本文件。一个文本文件称为“用户名”文本文件,而另一个称为“密码”文本文件。我正在创建一个登录程序。为了使用户成功登录,用户名的行号必须与密码的行号匹配。然而,由于某种原因,我的两个文件的 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;
}
4

1 回答 1

1

你没有推进你的LineNumberReader每一个循环。while循环负责推进您的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();

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

于 2013-01-20T02:02:18.817 回答