2015-04-06 43 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