2017-03-26 54 views
0

我檢查了幾個類似的問題,當我使用經常提示的答案時,本應該工作的條件沒有得到滿足。Java - 掃描程序NoSuchElementException:找不到行

有了這個代碼,

import java.util.Scanner; 

Scanner console = new Scanner(System.in); 

// ...various code here... 

public void printMenu() 
{ 
    while (true) 
    { 
     System.out.println("\nPlease make a selection:\n" 
       + "1) Access account\n" 
       + "2) Open a new Account\n" 
       + "3) Exit"); 

     String selection = console.nextLine(); 

     if (selection.equals("1")) enterPin(); 
     else if (selection.equals("2")) newOrReturning(); 
     else if (selection.equals("3")) 
     { 
      System.out.println("Thank you for using the BSU Banking App"); 
      System.exit(0); 
     } 
     else System.out.println("Invalid entry"); 
    } 
} 

我正在錯誤,

Exception in thread "main" java.util.NoSuchElementException: No line found 
    at java.util.Scanner.nextLine(Scanner.java:1540) 
    at Menu.printMenu(Menu.java:56) 
    at Menu.runMenu(Menu.java:31) 
    at Main.main(Main.java:29) 

有人建議while(console.hasNextLine())先於console.nextLine()使用,但是當我使用的是,

public void printMenu() 
{ 
    while (console.hasNextLine()) 
    { 
     System.out.println("\nPlease make a selection:\n" 
       + "1) Access account\n" 
       + "2) Open a new Account\n" 
       + "3) Exit"); 

     String selection = console.nextLine(); 

     if (selection.equals("1")) enterPin(); 
     else if (selection.equals("2")) newOrReturning(); 
     else if (selection.equals("3")) 
     { 
      System.out.println("Thank you for using the BSU Banking App"); 
      System.exit(0); 
     } 
     else System.out.println("Invalid entry"); 
    } 
} 

現在它甚至不執行代碼,暗示沒有nextLine。有什麼建議麼?我很抱歉,如果有我錯過的信息 - 如果有我會及時編輯。

編輯:錯誤地解釋了我的問題。

+1

而是要求我們解決這個給你的,你應該使用調試器。設置一個斷點,單步執行代碼以查看正在發生的事情,檢查程序正在使用的變量中的值/對象..... –

+0

請嘗試boolean trueOrFalse = true;然後把它放在while循環的測試條件中,然後在if(selection.equals(「3」){trueOrFalse = false;} – abcOfJavaAndCPP

+0

我很抱歉 - 我有更多的建議,而不是有人爲我做所有的工作。我會這樣做,謝謝 –

回答

0

請儘量將

public void printMenu() 
{  boolean trueOrFalse=true; 

     System.out.println("\nPlease make a selection:\n" 
       + "1) Access account\n" 
       + "2) Open a new Account\n" 
       + "3) Exit"); 

     String selection = console.nextLine(); 

    while (trueOrFalse) 
    { 


     if (selection.equals("1")) 
     { 
      enterPin(); 
      trueOrFalse=false; 
     } 
     else if (selection.equals("2")) 
     { 
      newOrReturning(); 
      trueOrFalse=false; 
     } 
     else if (selection.equals("3")) 
     { 
      System.out.println("Thank you for using the BSU Banking App"); 
      trueOrFalse=false; 
     } 
     else 
     { 
      System.out.println("Invalid entry"); 
      System.out.println("\nPlease make a selection:\n" 
       + "1) Access account\n" 
       + "2) Open a new Account\n" 
       + "3) Exit"); 

      selection = console.nextLine(); 
     } 
    } 
    System.exit(0); 
} 
相關問題