确保我的RNG不会根据用户输入的字符串崩溃

时间:2019-01-08 19:35:02

标签: java java.util.scanner

我制作了一个随机数生成器,如果有人使用这个不带数字的数字,它将崩溃 如何确定用户输入是否为字符串,不会崩溃,而是说“无效参数”?

static int random; 
static String string;
static Scanner scanner = new Scanner(System.in);
public static void main(String args[])  {


    System.out.println(getRandomNum());
    int guessResult =1;
    int randomGuess= 0;
    while(guessResult != -123) {

        System.out.print("Guess a number between 0 and 50");

        randomGuess = scanner.nextInt();
        guessResult = checkGuess(randomGuess);

    }

    System.out.println("Yes the random number is " + randomGuess);

}

public static int getRandomNum() {


    random = (int)(Math.random() * 51);
    return random;
}

public static int checkGuess(int guess) {

    if(guess == random) {

        return -123;

    }else {
        System.out.println("please retry " +guess + " was not correct");
        return guess;


    }

}

}

1 个答案:

答案 0 :(得分:1)

您可以将输入扫描包裹到try-catch块中:

try{
  randomGuess = scanner.nextInt();
  guessResult = checkGuess(randomGuess);
}
catch(Exception ex){
  System.out.println("Invalid argument");
}