如何将用户输入限制为整数1或2,并且不允许用户在java中输入除整数以外的任何内容?
问题描述:
我在这方面遇到了很多麻烦。我尝试过多种方式,但它仍然给我一个错误信息和崩溃。我想循环播放,直到用户输入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)
答
使用nextLine
而不是nextInt
,事后有例外处理。
boolean accepted = false;
do {
try {
listChoice = Integer.parseInt(scan.nextLine());
if(listChoice > 3 || listChoice < 1) {
System.out.println("Choice must be between 1 and 2!");
} else {
accepted = false;
}
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number!");
}
} while(!accepted);
答
你也可以在Switch Case语句中试试这个。
switch(listchoice)
{
case 1:
//Statment
break;
case 2:
//statement
break;
default:
System.out.println("Your error message");
break;
}
答
因为用户可以输入任何东西,你有一个线作为字符串读取:
String input = scan.nextLine();
一旦你做到了这一点,测试很简单:
input.matches("[12]")
All together:
String input = null;
do {
System.out.println("Enter either 1 or 2:");
input = scan.nextLine();
} while (!input.matches("[12]"));
int listChoice = Integer.parseInt(input); // input is only either "1" or "2"
+0
这是一个有趣的方法!我也会尝试一下!谢谢你! – sukiyo
使用'next'而不是'nextInt'添加'try/catch'来处理'NumberFormatException'...(显然使用'if'来检查它是1还是2) – Idos
@Idos谢谢!我为什么要用if语句?它不像循环一样循环。我不希望它停止要求用户输入1或2. – sukiyo
我的意思是使用'if' _inside_循环。 – Idos