为什么我的代码会给我一个错误?如果用户输入了错误的号码,代码是否应该让我输入新的有效号码?似乎它不会让我将喜爱改为新值。我怎么能解决这个问题?
package RobB;
import java.util.Scanner;
public class FavoriteNum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] num = new int[10];
int favorite = 0;
System.out.print("Enter your favorite number: ");
try {
favorite = scan.nextInt();
}
catch (Exception e) {
System.out.println("Enter an integer!");
System.out.print("Enter your favorite number: ");
favorite = scan.nextInt();
}
for (int i = 0; i < 10; i++) {
System.out.print("Enter a random number (" + Math.abs(((i + 1) - 10)) + " to go): ");
num[i] = scan.nextInt();
}
}
}
控制台输出:
Enter your favorite number: 11.1
Enter an integer!
Exception in thread "main" Enter your favorite number: 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 RobB.FavoriteNum.main(FavoriteNum.java:21)
扫描catch
子句中的输入似乎不是最好的主意。我建议使用do-while
循环,允许离开此循环的条件可能是boolean
标志,当您确认最终输入有效的Integer
时,状态将被更改。您可能还想考虑使用Scanner
的hasNextInt()
方法来检查是否提供了正确的输入,如果在您的情况下不是真的需要,则不会抛出任何异常。这是ronhash答案的一点变化,但使用do-while
循环:
boolean validInput = false;
do {
try {
System.out.print("Enter your favourite number: ");
favorite = scan.nextInt();
validInput = true; }
catch (Exception e) {
System.out.println("Enter an integer!"); }
} while (!validInput)
编辑:我编辑了代码,因为前一个代码效率低且错误。
这是一个带有while循环的替代方法:
boolean validInput = false;
while (!validInput) {
try {
System.out.print("Enter your favourite number: ");
favorite = scan.nextInt();
validInput = true;
}
catch (Exception e) {
System.out.println("Enter an integer!");
}
}