Java中循环中try-catch的问题

时间:2014-07-11 23:10:45

标签: java

我是新来的,我正在学习Java。在我的一个程序中,我做了一个猜谜游戏。猜测游戏应该一直要求用户输入一个猜测,直到他们猜对了。

这是我的代码:

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        final int minValue = 1;
        final int maxValue = 10;
        final boolean displayHints = true;  // Display whether the number is too high or too low when guessed incorrectly?
        int tries = 1;
        int guess = 0;      // We need to give 'guess' a (temporary) value or else the 'while' loop will create an error
        boolean error = false;

        Random generator = new Random();                        // Create scanner 'generator'
        int random = generator.nextInt(maxValue) + minValue;    // Define 'random' variable with a random value
        if (random == guess) {  // In case 'random' = 'guess'
            guess = -852654;
        }
        Scanner input = new Scanner(System.in); // Create a scanner
        System.out.println("Random number: " + random); // Hey, no cheating! (for debugging purposes)

        System.out.println("Try to guess the magic number! (from " + minValue + " to " + maxValue + ")");
        while (random != guess) {
            do {    // Supposed to ask the user to input a number until they enter a valid number. This is the part of the code that is not working.
                System.out.println("\nInput your guess now!");
                try {
                    guess = input.nextInt();
                    error = false;
                } catch (InputMismatchException e) {
                    System.err.println("That's not a number!\n");
                    error = true;
                    continue;
                }
            } while (error);

            if (guess == random) {
                System.out.println("Correct!");
                System.out.println("Number of tries: " + tries + ".");
                input.close();
            } else {
                tries++;
                if (displayHints) {
                    if (guess < random) {
                        System.out.println("Sorry, too low!");
                    } else if (guess > random) {    // not strictly necessary
                        System.out.println("Sorry, too high!");
                    }
                } else {
                    System.out.println("Sorry, that was not the right number");
                }
            }
        }
    }
}

代码非常明显,因为我做了很多评论。但问题是,当用户输入无效的整数(例如&#39; banana&#39;)时,而不是说&#34;那不是数字!&#34;并要求另一个数字,代码做这样的事情:

Random number: 9
Try to guess the magic number! (from 1 to 10)

Input your guess now!
banana

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!

Input your guess now!
That's not a number!

Input your guess now!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!

That's not a number!


Input your guess now!
That's not a number!


Input your guess now!
That's not a number!


Input your guess now!
That's not a number!


Input your guess now!
That's not a number!


Input your guess now!
That's not a number!


Input your guess now!
That's not a number!

其余代码完美无缺。

5 个答案:

答案 0 :(得分:2)

你忘了消耗糟糕的输入。尝试使用catch块中输入错误的行。

} catch (InputMismatchException e) {
    System.err.println("That's not a number!\n");
    error = true;
    String notANumber = input.nextLine();  // add
    continue;
}

此外,println已在任何正在打印的内容的末尾添加换行符,因此无需在您正在打印的字符串中添加其他\n个字符。

通过上述更改,这里是do-while循环的示例输入/输出:

Input your guess now!
banana
That's not a number!


Input your guess now!
8

答案 1 :(得分:2)

正如rgettman所解释的那样,您需要消耗错误的输入,因为如果InputMismatchException上升,则不会消耗该令牌。

另一种解决方案是,为了使您免受try/catch阻止,可以使用hasNextInt()

if (input.hasNextInt())
{
  int guess = input.readInt();
}
else
{
  if (input.hasNextLine())
    input.nextLine();
}

答案 2 :(得分:1)

扫描仪实际上从未获得有效输入,因此当您到达guess = input.nextInt();

时反复抓取香蕉

我的修复方法是将输入作为字符串读入并将其解析为整数。然后,您只需要抓住NumberFormatException而不是InputMismatchException

我就是这样做的:

try {
    guess = Integer.parseInt(input.next());
    error = false;
} catch (NumberFormatException e) {
    System.err.println("That's not a number!\n");
    error = true;
}

答案 3 :(得分:0)

正如许多人所提到的,你需要消耗错误的输入。我遇到了一个非常类似的问题,我在这里没有看到合适的答案,但我在其他地方找到了答案。

尝试将以下行放在catch块的末尾。

input.nextLine();

这将清除缓冲区并解决您的问题。

答案 4 :(得分:0)

最简单的方法就是改变

guess = input.nextInt();

guess = Integer.valueOf(input.next());

只有改变一小段代码才能解决问题。复制并试一试!

但我仍然认为你的代码看起来很混乱。我会做这样的事情

  public static void main(String[] args) {



    Scanner input = new Scanner(System.in);
    Random r = new Random ();
    int x = r.nextInt(10);
    int y = 0;
    int counter=0;


    do{
    System.out.println("Guess a number between 0-10: ");

    try{
    y = Integer.valueOf(input.next());
    }catch (Exception e){
        System.out.println("That is not a number ");
        continue;
    }
    counter ++;

    if (counter>5){
    System.out.println("So you still don't know how to guess quicker?");
    }

    if (y<x){
    System.out.println("You gessed wrong, the number is higher");
    }

    else if (y>x){
    System.out.println("You gessed wrong, the number is lower");
    }

    else if (y==x)
        System.out.println("You gessed right, the number is: " + x);

        }while(y!=x);

    System.out.println("You guessed the number in: " + counter + " times");
    if(counter <=4){
 System.out.println("You found out how to guess the number quickly");
    }
 }