通过扫描仪保证整数输入的更简单方法?
-
19-08-2019 - |
题
对于我正在编写的程序,我需要向用户询问 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;
}
}
在哪里 inputScanner
是一个扫描仪。当然有更好的方法吗?
解决方案
扫描程序的正则表达式,是吗?为什么不检查它是否符合 “^ [1-8] $” 第一?
其他提示
使用nextInt()已经改善比较简单地使用next()方法。而在这之前,你可以使用hasNextInt(),以避免哈氏所有这一堆无用的异常。
从而造成这样的:
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
我不得不做一个图形界面计算器(只适用于整数),问题是,这 这些测试并没有允许任何异常被抛出,如果输入不 整数。所以我不能使用
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
由于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
希望这有助于:)
Apache Commons 是您的朋友。看 NumberUtils.toInt(字符串, int)
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; }
}
}
我总是喜欢在满弦拉,所以你可以肯定的是,用户按下回车键。如果你只是使用inputScanner.nextInt()
您可以将两个int
s上线,它会在一拉,那么其他。
实施例的代码:
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
的阵列也可以用于存储整数。
您可以尝试这样的事:
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();
}
}
不隶属于 StackOverflow