我希望用户输入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.");
。
答案 0 :(得分:0)
用户无需重新输入输入。一旦没事。
您要求输入三次:
int guess = keyboard.nextInt(); // here
try{
input = keyboard.nextInt(); // here
}catch (InputMismatchException e){
guess = keyboard.nextInt(); // and here
System.out.println("Invalid.");
}
第一个是抛出异常。由于没有捕获到该异常,因此它终止了应用程序。
看起来你只想要这个:
int guess;
try {
input = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid.");
return;
}
代替return
区块末尾的catch
,您可能会做其他事情,无论您想做什么都取决于您。但是,如果guess
从未设置为有效的int
,则方法中的其余逻辑将不适用,因此默认情况下我只是退出此方法。
但基本上,如果您希望用户输入一次输入,那么只需要一次。每当你想要处理异常时,请将代码抛出try/catch
来处理它。
答案 1 :(得分:0)
您的错误正在这一行:int guess = keyboard.nextInt();
,它没有被try/catch
语句包围。大家都知道,每次拨打Scanner.nextInt()
时,都要求换行。试着这样做:
int guess = -1; // This will be an invalid input
try{
guess = keyboard.nextInt();
}catch (InputMismatchException e){
// Because guess is already -1, "invalid" will be printed out by
// Below if statements
}
这样,如果用户输入无效猜测,则使用已创建的if语句来处理它。