java 通过扫描仪保证整数输入的更简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/471013/
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
Easier way to guarantee integer input through Scanner?
提问by Logan Serman
For a program I am writing, I need to ask a user for an integer between 1 and 8. I've tried multiple (cleaner) ways of doing this but none of them worked, so I'm left with this:
对于我正在编写的程序,我需要向用户询问 1 到 8 之间的整数。我尝试了多种(更干净的)方法来做到这一点,但没有一个有效,所以我只剩下这个了:
int x = 0;
while (x < 1 || x > 8)
{
System.out.print("Please enter integer (1-8): ");
try
{
x = Integer.parseInt(inputScanner.next());
}
catch(NumberFormatException e)
{
x = 0;
}
}
Where inputScanneris a Scanner. Surely there is a better way?
inputScanner扫描仪在哪里。当然有更好的方法吗?
回答by Paul Tomblin
Scanner does regular expressions, right? Why not check if it matches "^[1-8]$" first?
Scanner 做正则表达式,对吧?为什么不先检查它是否匹配“^[1-8]$”?
回答by gizmo
Using the nextInt() is already an improvement compare to simply using the next() method. And before that, you can use the hasNextInt() to avoid haing all this bunch of useless exceptions.
与简单地使用 next() 方法相比,使用 nextInt() 已经是一种改进。在此之前,您可以使用 hasNextInt() 来避免所有这些无用的异常。
Resulting in something like this:
结果是这样的:
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
回答by goalaleo
I had to do a graphic interface calculator (works only with Integers), and the problem was, that the Tests didn't allow any Exceptions to be thrown if the input wasn't Integer. So I couldn't use
我不得不做一个图形界面计算器(仅适用于整数),问题是,如果输入不是整数,测试不允许抛出任何异常。所以我无法使用
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
Because Java programs generally treat an input to a JTextField as a String I used this:
因为 Java 程序通常将 JTextField 的输入视为字符串,所以我使用了这个:
if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
goodforyou
} else {
dosomethingelse
}
// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9
hope this helps :)
希望这可以帮助 :)
回答by Jason Carlson
You could try something like this:
你可以尝试这样的事情:
Scanner cin = new Scanner(System.in);
int s = 0;
boolean v = false;
while(!v){
System.out.print("Input an integer >= 1: ");
try {
s = cin.nextInt();
if(s >= 1) v = true;
else System.out.println("Please input an integer value >= 1.");
}
catch(InputMismatchException e) {
System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
cin.next();
}
}
回答by Joe Phillips
String input;
int number;
while (inputScanner.hasNextLine())
{
input = inputScanner.nextLine();
if (input.equals("quit")) { System.exit(0); }
else
{
//If you don't want to put your code in here, make an event handler
//that gets called from this spot with the input passed in
try
{
number = Integer.parseInt(input);
if ((number < 1) || (number > 8))
{ System.out.print("Please choose 1-8: "); }
else { /* Do stuff */ }
}
catch (NumberFormatException e) { number = 0; }
}
}
I always like to pull in the full string so you can be sure that the user pushed the Enter button. If you just use inputScanner.nextInt()you can put two ints on a line and it will pull in one, then the other.
我总是喜欢拉入完整的字符串,这样您就可以确定用户按下了 Enter 按钮。如果您只是使用inputScanner.nextInt(),则可以将两个ints 放在一条线上,它会拉入一个,然后再拉入另一个。
回答by Brandon DuRette
Apache Commons is your friend. See NumberUtils.toInt(String, int)
Apache Commons 是您的朋友。参见NumberUtils.toInt(String, int)
回答by kevan1881
Example code:
示例代码:
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
An array can also be used to store the integer.
数组也可用于存储整数。

