Java-扫描器NoTouchElementException:未找到任何行
我检查了几个类似的问题,当我使用经常被建议的答案时,一个本应该有效的条件没有得到满足 有了这个代码Java-扫描器NoTouchElementException:未找到任何行,java,java.util.scanner,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
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)
有人建议在console.nextLine()
之前使用while(console.hasNextLine())
,但当我使用它时
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");
}
}
现在它甚至不执行代码,这意味着没有下一行。有什么建议吗?我很抱歉,如果有我错过的信息-如果有,我会及时编辑
编辑:错误地解释了我的问题。请尝试此操作
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);
}
您应该使用调试器,而不是要求我们为您解决此问题。设置断点,单步执行代码以查看发生了什么,检查程序正在使用的变量中的值/对象…..请尝试布尔值trueOrFalse=true;然后将它放在while循环的测试条件中,然后放在if(selection.equals(“3”){trueOrFalse=false;}我很抱歉-我更多的是征求建议,而不是让某人为我做所有的跑腿工作。我会这样做的,谢谢。另外,在while循环外部获取字符串初始化,并在外部提示用户一次,在内部,如果用户不符合条件,则对其进行重新验证