Java 检查userInput是否为数字,但出现异常
我正在检查用户的输入是否为int 以下是我目前的代码:Java 检查userInput是否为数字,但出现异常,java,Java,我正在检查用户的输入是否为int 以下是我目前的代码: static int readInt(Scanner userInput) { int intValue = 0; try { System.out.print("Please enter a number:"); intValue = Integer.parseInt(userInput.nextLine()); } catch (NumberFormatException ex) {
static int readInt(Scanner userInput) {
int intValue = 0;
try {
System.out.print("Please enter a number:");
intValue = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
Input.readInt(userInput);
}
return intValue;
}
问题是:如果我先给它一个不是数字的输入,然后给它一个数字,它总是返回0。如果我第一次给它一个数字,它会返回我给它的数字
我错过了什么?
提前谢谢
编辑:我只允许使用Integer.parseInt和异常。看起来您没有在catch中设置变量
intValue = Input.readInt(userInput);
为了避免您的问题,在catch块中,您需要将这个
Input.readInt(userInput)
分配给您的变量。像这样:
intValue = Input.readInt(userInput);
递归在这里是开销。使用循环:
Integer result = null;
do {
System.out.print("Please enter a number:");
try {
result = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
System.out.print("Not a number");
}
} while(result==null);
return result;
您没有分配
Input.readInt(userInput)的返回值
到您的intValue
考虑将输入代码包装在while
-循环中,以确保程序仅在收到有效输入时继续前进。如果您只允许使用Integer.parseInt和异常,请编辑您的问题并添加此要求。这就解决了问题,谢谢!所以我根本不需要把“Input.readInt(userInput);”放在我的捕获中,对吗?