[英]Java Login Codes Reading multiple lines from file not working
我在下面获得此代码以执行简单的密码(哈希)检查功能。 但是我遇到了一个问题,代码似乎仅适用于文件中的单行数据,检查适用于Line1而不适用于Line2,我不确定这是什么错误。 数据如下所示
结果应该是与Line1或2匹配的hashP。但是最终仅与Line1匹配
260670134225f2a24b59121739fec73584b0ddb6b49c39e31bd1df5483ac144d //Line1
cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90 //Line2
码:
public static void LoginMenu() {
System.out.println("Please Enter Your Password: ");
Scanner UserPass = new Scanner(System.in);
String UserP = UserPass.nextLine();
String hashedP = Utility.getHash(UserP);
File file = new File("admin.dat");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
if (!(fileline.equals(hashedP))) {
System.out.println("Login Failed!");
LoginMenu();
}
else {
System.out.println("Login Successful.\n");
AdminMenu();
}
}
scanner.close();
}
catch (FileNotFoundException exc) {
exc.printStackTrace();
}
}
让我们分析一下这一部分:
while (scanner.hasNextLine()) {
String fileline = scanner.nextLine();
if (!(fileline.equals(hashedP))) {
System.out.println("Login Failed!");
LoginMenu();
}
else {
System.out.println("Login Successful.\n");
AdminMenu();
}
}
while
循环。 hashedP
检查它。 您甚至都无法到达文件的第二行,它的速度太快了。
您应该重构循环以更加努力:
boolean failed = true;
while (scanner.hasNextLine())
{
String fileline = scanner.nextLine();
if (fileline.equals(hashedP))
{
failed = false;
System.out.println("Login Successful.\n");
AdminMenu();
}
}
if(failed)
{
System.out.println("Login Failed!");
LoginMenu();
}
与此无关,如果以某种方式可以避免,则递归调用函数绝不是一个好主意。
在这种情况下,例如, admin.dat
和新的stdin
扫描程序将在输入错误密码后多次打开,而密码设计不正确。
我建议使用while(true)
循环代替读取密码并在此之前做其他所有事情:
public static void LoginMenu()
{
ArrayList<String> hashes = new ArrayList<String>();
File file = new File("admin.dat");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
hashes.add(scanner.nextLine());
}
scanner.close();
}
catch (FileNotFoundException exc)
{
exc.printStackTrace();
return;
}
Scanner UserPass = new Scanner(System.in);
while (true)
{
System.out.println("Please Enter Your Password: ");
String UserP = UserPass.nextLine();
String hashedP = Utility.getHash(UserP);
if (hashes.contains(hashedP))
{
System.out.println("Login Successful.\n");
AdminMenu();
break;
}
System.out.println("Login Failed!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.