Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的try-catch-inside-while循环存在问题_Java - Fatal编程技术网

Java中的try-catch-inside-while循环存在问题

Java中的try-catch-inside-while循环存在问题,java,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 min

我是新来的,我正在学习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");
                }
            }
        }
    }
}

代码的其余部分工作正常。

您忘记使用错误的输入。尝试使用
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

正如Targetman所解释的,您需要使用错误的输入,因为如果出现
inputmaschException
,则不会使用令牌

另一种解决方案是使用
hasnetint()
,将您从
try/catch
块中解救出来:


扫描仪实际上从未获得有效的输入,因此当您到达
guess=input.nextInt()时,它会反复抓取香蕉

我的解决办法是将输入作为字符串读入,并将其解析为整数。然后您只需要捕获一个
NumberFormatException
,而不是
inputmaschException

我会这样做:

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

正如许多人提到的,您需要使用错误的输入。我遇到了一个非常类似的问题,我在这里没有看到合适的回答,但我在别处找到了一个

试着把下面的线放在你的挡块末端

input.nextLine();

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

最简单的方法就是更改

guess = input.nextInt();

这将解决问题,只需更改一小行代码。复制并尝试它

但我还是觉得你的代码看起来很乱。我会这样做

  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");
    }
 }
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
Random r=新的Random();
int x=r.nextInt(10);
int y=0;
int计数器=0;
做{
System.out.println(“猜一个介于0-10之间的数字:”);
试一试{
y=整数.valueOf(input.next());
}捕获(例外e){
System.out.println(“这不是一个数字”);
继续;
}
计数器++;
如果(计数器>5){
System.out.println(“那么你还不知道如何更快地猜?”;
}
如果(yx){
System.out.println(“您选错了,数字更低”);
}
else如果(y==x)
System.out.println(“你选对了,数字是:”+x);
}而(y!=x);
System.out.println(“您猜到了:“+counter+”times”中的数字);

if(计数器)
\n
将给出一个空行作为间隔。谢谢!但是,请注意,
input.readLine();
应该是
input.nextLine();
。这就是我最后做的:if(input.hasNextInt()){guess=input.nextInt();error=false;}else{System.err.println(“这不是一个数字!”);if(input.hasNextLine()){input.nextLine();}错误=true;}
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");
    }
 }