簡體   English   中英

Java中while循環內try-catch的問題

[英]Problems with try-catch inside while loop in 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");
                }
            }
        }
    }
}

該代碼是不言自明的,因為我做了很多評論。 但是,問題在於,當用戶輸入無效的整數(例如“香蕉”)時,而不是說“那不是數字!” 並詢問另一個數字,代碼將執行以下操作:

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!

其余代碼工作完美。

您忘了消耗不好的輸入。 嘗試使用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

正如rgettman解釋的那樣,您需要使用錯誤的輸入,因為如果InputMismatchException了,則令牌不會被使用。

hasNextInt()您免於try/catch塊的另一種解決方案是使用hasNextInt()

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

掃描程序實際上從未獲得有效的輸入,因此當您到達guess = input.nextInt();時,它會一遍又一遍地反復抓香蕉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;
}

正如許多人提到的那樣,您需要消耗錯誤的輸入。 我遇到了一個非常相似的問題,在這里沒有看到適當的答復,但是我在其他地方找到了。

嘗試將以下行放在catch塊的末尾。

input.nextLine();

這將清除緩沖區並應解決您的問題。

最簡單的方法就是改變

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");
    }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM