如何在.txt文件中搜索字符串和哈希码? (JAVA)

问题描述 投票:-2回答:1

提示:我正在编写一个登录程序,询问用户的用户名和密码。所有用户信息都存储在password.txt文件中,密码存储为哈希码。如果用户输入的无效用户名或密码与条目中的散列不具有相同的散列,则程序应打印“登录失败”。如果用户输入有效的用户名,并且密码具有与在条目中使用哈希,然后程序应该打印“登录成功”。

password.txt文件设置如下:

Real name:username:password_hash

问题:如何在.text中搜索字符串和哈希码?

这是我现在的代码:

   public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            Scanner sf = new Scanner("passwords.txt");
            String Username;
            String Password;

            System.out.println("Login ");
            System.out.println("Please Enter Username: ");
            Username = sc.next();

            System.out.println("Please Enter Password: ");
            Password = sc.next();

            String login = Username + ":" + Password.hashCode();
            System.out.println(login);

            while(sf.hasNextLine()){
                    if((login.equals(sf.nextLine().trim()))){
                            System.out.println("Login Successful!");
                            break;
                    }

                    if(!(login.equals(sf.nextLine().trim()))){
                            System.out.println("Login Unsuccessful!");

                    }
            }

我正在尝试在代码中搜索看起来像username:hashcodePassword的String

问题:代码不打印if语句,并在运行程序时给出了这个错误

错误:

Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.util.Scanner.nextLine(Scanner.java:1540)
        at LoginApplication.main(LoginApplication.java:29)
java java.util.scanner bufferedreader equals readfile
1个回答
1
投票

简单的解释:你的代码检查文件是否有下一行,所以检查第一个嵌套if,但是在这里它从文件中读取一行,并将指向该文件的指针移动到下一行。然后它检查下一个if语句,并在此处读取文件的另一行。出现问题的原因是您实际上一次读取两行文件。

解决方案是

while(sf.hasNextLine()) {
                final String currentLine = sf.nextLine().trim();
                if(login.equals(currentLine)){
                        System.out.println("Login Successful!");
                        break;
                } else {
                        System.out.println("Login Unsuccessful!");
                }
        }

那么如果你需要更多if语句,你可以使用currentLine变量而不是读取另一行文件。

© www.soinside.com 2019 - 2024. All rights reserved.