检查用户的输入是否在范围内并且是整数(Java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19129416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a User's Input is in Range and is an Integer (Java)
提问by Tyler Waite
I am working on a project (a game) and one of the requirements is to have warnings if they enter an option outside of the range (1-8) and if they enter a character. If the user enters an invalid number, the menu appears and asks them again which option they would like. If they enter a character, the program should ask them to enter an integer and ask for input again. This is what I have so far. It correctly identifies a number out of range and recalls the menu. It also identifies a character (invalid input), but does open input for the user to enter a correct option. How can I check both conditions?
我正在做一个项目(一个游戏),其中一个要求是,如果他们输入了超出范围 (1-8) 的选项并且输入了一个字符,就会发出警告。如果用户输入了无效的数字,则会出现菜单并再次询问他们想要哪个选项。如果他们输入一个字符,程序应该要求他们输入一个整数并再次要求输入。这是我到目前为止。它正确识别超出范围的数字并调用菜单。它还标识一个字符(无效输入),但会为用户打开输入以输入正确的选项。如何检查这两个条件?
Thanks, Tyler
谢谢,泰勒
int userChoice = scnr.nextInt();//<-- use this variable
if (userChoice.hasNextInt() == false)
{
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
// Variable used for storing what the user's main menu choice
if (0 > userChoice || userChoice > 8)
{
System.out.println("Error: Invalid Menu Selection.");
System.out.println("");
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
userChoice = scnr.nextInt();
}
回答by Balaji Krishnan
you are using the hasNextInt()
method on primitive int
to see if the input is interger. instead use this:
您正在使用hasNextInt()
原始方法int
来查看输入是否为整数。而是使用这个:
int userChoice ;
try{
userChoice =scnr.nextInt();//<-- use this variable
}
catch(InputMismatchException ime){
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
likewise use the same logic inside the if condition also
同样在 if 条件中也使用相同的逻辑
回答by Yasa
Better to go with Switch-Case statement within a loop. Java JDK 1.7 also supports 'string' in switch-case now.
最好在循环中使用 Switch-Case 语句。Java JDK 1.7 现在也支持 switch-case 中的“字符串”。
回答by Thusitha Thilina Dayaratne
try{
int userChoice = scnr.nextInt();
if(userChoice > 0 && userChoice <9){
// your logic
}else{
System.out.println("Invalid choice");
showMenu();
}
}catch(Exception e){
System.out.println("Invalid choice");
showMenu();
}
public void showMenu(){
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
}
回答by lkamal
First of all there is correction to be made on the sequence nextInt()
and hasNextInt()
is invoked. First one is used to read the value from input, and second is used to see whether the value type is int
. So you have to invoke hasNext[Type]()
followed by `next[Type].
首先,要对序列进行更正nextInt()
并hasNextInt()
调用。第一个用于从输入中读取值,第二个用于查看值类型是否为int
。所以你必须在调用hasNext[Type]()
后跟 `next[Type]。
Secondly, since nextInt()
is returning an int
, so it is incorrect to invoke hasNextInt()
on the userChoice
variable.
其次,由于nextInt()
返回的是int
,因此调用hasNextInt()
该userChoice
变量是不正确的。
Let's correct those two first as below.
让我们首先纠正这两个,如下所示。
if (scnr.hasNextInt()) {
int userChoice = scnr.nextInt();
} else {
// input is not an int
}
Now let's correct your code to get a valid int
, also to print the instructions and ask for the input again for invalid inputs.
现在让我们更正您的代码以获得有效的int
,同时打印说明并再次要求输入以获取无效输入。
Scanner scnr = new Scanner(System.in);
boolean incorrectInput = true;
int userChoice = -1;
while (incorrectInput) {
if (scnr.hasNextInt()) {
userChoice = scnr.nextInt();
// Variable used for storing what the user's main menu choice
if (0 >= userChoice || userChoice > 8) {
System.out.println("Error: Invalid Menu Selection.");
System.out.println("");
System.out.println("Available Actions:");
System.out.println("(1) Print Market Prices");
System.out.println("(2) Print Detailed Statistics");
System.out.println("(3) Buy Some Sheep");
System.out.println("(4) Buy a Guard Dog");
System.out.println("(5) Sell a Sheep");
System.out.println("(6) Sell a Guard Dog");
System.out.println("(7) Enter Night Phase");
System.out.println("(8) Quit");
System.out.println("What would you like to do?");
} else {
incorrectInput = false;
}
} else {
scnr.next();
System.out.println("Error: Menu selection must be an integer! Please try again:");
}
}
System.out.println("userChoice = " + userChoice);
回答by yglodt
Or, you can use the powerful IntegerValidator
from Apache Commons Validator:
或者,您可以使用IntegerValidator
来自Apache Commons Validator的强大功能:
if (new IntegerValidator().isInRange(Integer value, int min, int max)) {
// value is in range ...
}