【发布时间】:2016-09-27 21:51:26
【问题描述】:
我希望用户输入一个介于 0-9 之间的数字。如果他们输入了超出此范围的数字(负数或大于 9 的数字),则他们输入了无效输入。此外,我想使用 try catch 块来识别不正确的输入类型(字符串),并打印无效。
用户无需重新输入。一次就好。
到目前为止我所尝试的:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;
public class guessinggame
{
public static void main (String[] args)
{
int randomNumber = new Random().nextInt(10);
System.out.println("My number is " + randomNumber + ". ");
System.out.println("I’m thinking of a number between 0 and 9.");
System.out.println("What is your guess:");
Scanner keyboard = new Scanner(System.in);
int guess = keyboard.nextInt();
try{
input = keyboard.nextInt();
}catch (InputMismatchException e){
guess = keyboard.nextInt();
System.out.println("Invalid.");
}
if (guess < randomNumber) {
System.out.println("your guess was too low.");
}else if (guess > randomNumber){
System.out.println("your guess was too high.");
}else if (guess == randomNumber){
System.out.println("your guess was correct.");
}else if (guess < 0){
System.out.println("Invalid.");
}else if (guess > 9){
System.out.println("Invalid.");
}
}
}
这只是我的 try catch 块:
try{
input = keyboard.nextInt();
}catch (InputMismatchException e){
guess = keyboard.nextInt();
System.out.println("Invalid.");
}
我遇到的问题是,在编译时,我输入一个字符串输入,例如“abc”,程序会创建这种格式的运行时错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at guessinggame.main(guessinggame.java:17)
当所有 应该 在输入字符串后显示为:
Invalid. 根据我的 catch 块中的声明 System.out.println("Invalid.");。
【问题讨论】:
标签: java validation types try-catch