Java - Scanner NoSuchElementException:找不到行

时间:2017-03-26 02:25:19

标签: java java.util.scanner

我已经检查了几个类似的问题,当我使用经常提出的答案时,应该有效的条件没有得到满足。

使用此代码,

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"); } } 时,

vFile

现在它甚至没有执行代码,暗示没有nextLine。有什么建议?如果有错过的信息我会道歉 - 如果有的话我会立即编辑。

编辑:错误地解释了我的问题。

1 个答案:

答案 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);
}