我在这方面遇到了很多麻烦。我尝试过多种方式,但它仍然给我一个错误信息和崩溃。我想循环播放,直到用户输入1或2如何将用户输入限制为整数1或2,并且不允许用户在java中输入除整数以外的任何内容?
System.out.println("Please choose if you want a singly-linked list or a doubly-linked list.");
System.out.println("1. Singly-Linked List");
System.out.println("2. Doubly-Linked List");
int listChoice = scan.nextInt();
//Restrict user input to an integer only; this is a test of the do while loop but it is not working :(
do {
System.out.println("Enter either 1 or 2:");
listChoice = scan.nextInt();
} while (!scan.hasNextInt());
它给我这个错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.main(Main.java:35)
使用'next'而不是'nextInt'添加'try/catch'来处理'NumberFormatException'...(显然使用'if'来检查它是1还是2) – Idos
@Idos谢谢!我为什么要用if语句?它不像循环一样循环。我不希望它停止要求用户输入1或2. – sukiyo
我的意思是使用'if' _inside_循环。 – Idos