尝试Catch Block Not Catching String Input(InputMismatchException)

时间:2016-09-27 00:36:25

标签: java exception-handling try-catch inputmismatchexception

我需要阻止用户输入字符串值。

这是我迄今为止所尝试的内容。

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();
        guess1(guess);


        int input = 0;


            try{
                input = keyboard.nextInt();

            }catch (InputMismatchException e){
                int guess = keyboard.nextInt();
                System.out.println("Invalid.");
            }



           if (guess < randomNumber) {
                System.out.print("your guess was too low.");
           }else if (guess > randomNumber){
                System.out.print("your guess was too high.");
            }else if (guess == randomNumber){
                System.out.print("your guess was correct.");
        }
    }
}

我收到的错误是:Duplicate local variable guess阻止程序编译,但是我想我也错过了让这个程序做我想做的事情。

它只需接受整数值作为0-9之间的输入。其他任何内容(包括字符串)都应返回为无效。

3 个答案:

答案 0 :(得分:1)

编译器给出了错误,因为您已声明guess两次:

  • int guess = keyboard.nextInt();
  • 开头
  • 然后再次使用int guess = keyboard.nextInt();的catch子句

另请注意,您在代码中多次readInt(),这意味着您尝试多次获取用户输入。您应该在代码中引用guess

如果您经常遇到编译错误等问题,可能需要使用Eclipse等IDE。

答案 1 :(得分:1)

主要错误是您在guess块中重新声明catch

如果输入了无效数据,您真正需要做的是loop

int guess = -1;  // some magic number
while (guess <= -1) {  // we do not want negative number
    try{
            guess = keyboard.nextInt();
        }catch (InputMismatchException e){
            System.out.println("Invalid - try again.");
            continue;
        }

    if (guess >= 0) {
        break;
    }
    System.out.println("We want between 0 and 9 - try again.");
}

// now we have valid value for guess

修改

根据新要求

   int guess = -1;  // some magic number
    try{
            guess = keyboard.nextInt();
        }catch (InputMismatchException e){
            // do not need to do anything
        }

    if (guess < 0) {
            System.out.println("Invalid - will exit.");
            System.exit(-1); 
    }
// now we have valid value for guess

答案 2 :(得分:0)

fmincon

应该只是

int guess = keyboard.nextInt();