2015-04-06 44 views
0

我在下面得到了下面的代码来做一个简单的密码(散列)检查功能。但是我遇到了一个问题,代码似乎只适用于文件中的单行数据,该检查适用于Line1,但不适用于Line2,我不确定哪里出错。数据显示如下Java登录码从文件中读取多行不工作

的结果应该是hashedP只要符合1号线或2,但是最终匹配一号线仅

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(); 
    } 
} 
+0

究竟什么是您的预期输出,什么是实际输出? – 2015-04-06 10:29:51

+0

预期的输出应该是散列P匹配文件中的任何行,但它最终只匹配Line1 – 2015-04-06 11:28:31

回答

2

我们来分析一下这个部分:

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(); 
    } 
} 
  1. 我们进入while循环。
  2. 我们从文件中读取第一行。
  3. 我们根据hashedP检查它。
    3.1。如果匹配,我们将显示管理员屏幕。
    3.2。如果不匹配,我们会提示用户重新登录。

你甚至没有到达文件的第二行,它失败太快。
你应该重构你的循环更加努力:

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!"); 
    } 
} 
+0

感谢您的建议,我会看看=) – 2015-04-06 11:58:20