当前位置: 首页 > 知识库问答 >
问题:

如何在我的程序中使用try/catch/last过滤扫描仪输入错误?

司信厚
2023-03-14

我写了一个小猜谜游戏,你必须猜一个随机数。我完成了这个程序,但我想做的最后一件事是:当用户应该输入一个数字及其和InputMissmatching错误或其他错误时,系统告诉他他必须输入一个大于0的数字。但在这个do-while循环之后,扫描仪的变量不再工作!如何设置try/catch/finally循环,以仅获取整数,而不是整数或0时不崩溃?

问题是guessNumber和numberOfUser变量现在还没有初始化!行:37,53那么在try/catch循环中我需要改变什么呢?

package gessinggame;

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

public class GessingGame {

    public static void main(String[] args) {




//<editor-fold desc="Start Variables and Objects">

        Random random = new Random();
        Scanner input = new Scanner(System.in);

        int counter = 0;
        int numberOfUser;
        int guessNumber;
        int x = 1;
        System.out.print("Try to guess my number! What should be the highest number I can go up to?: ");
        do{
        try{
            numberOfUser = input.nextInt();
            guessNumber = random.nextInt(numberOfUser);
            x = 2;
        }catch(Exception e)
        {
            System.out.print("That doesn't work! Please enter an integer higher than 0 :");
            x = 1;
        }
        }while(x == 1);
//</editor-fold>

//<editor-fold desc="do-while loop (higher/lower/equal)">

        System.out.println("Try to guess my number! Its from 0 to " + numberOfUser + " !");
        System.out.println("---------------------------------------------------");

        do{

                int userguess = input.nextInt();

                    if(userguess > numberOfUser)
                    {
                    System.out.println("Oh man, at the beginning you said that the highest number is: " + numberOfUser);
                    }
                    else{       
                            if(userguess < 0)
                            {
                            System.out.println("My number is always taller than 0");
                            } else{  
                                    if(guessNumber < userguess)
                                    {
                                        System.out.println("lower");
                                        counter++;
                                    }
                                    if(guessNumber > userguess) 
                                    {
                                        System.out.println("higher");
                                        counter++;
                                    }
                                    if(userguess == guessNumber) 
                                    {
                                        counter++;
                                        break;
                                    }
                                    }
                        }
            }while(true);

//</editor-fold>

//<editor-fold desc="print final result">

        System.out.println("You guessed my number! My number was: " + guessNumber + "! You needed " + counter + " attempts!");

//</editor-fold>
    }

}

共有2个答案

吕利
2023-03-14

所以问题是,首先你当然需要捕获异常。在try catch中,你必须清除缓冲区,然后使用input.nextLine();

所以这应该可以:

public static void main(String[] args)
{

    // <editor-fold desc="Start Variables and Objects">

    Random random = new Random();
    Scanner input = new Scanner(System.in);

    int counter = 0;
    int numberOfUser = 0;
    int guessNumber = 0;
    int x = 1;
    System.out.print("Try to guess my number! What should be the highest number I can go up to?: ");
    do
    {
        try
        {
            numberOfUser = input.nextInt();
            guessNumber = random.nextInt(numberOfUser);
            x = 2;
        }
        catch (Exception e)
        {
            System.out.print("That doesn't work! Please enter an integer higher than 0 :");
            x = 1;
        }
    } while (x == 1);
    // </editor-fold>

    // <editor-fold desc="do-while loop (higher/lower/equal)">

    System.out.println("Try to guess my number! Its from 0 to " + numberOfUser + " !");
    System.out.println("---------------------------------------------------");

    do
    {

        int userguess = 0;
        try
        {
            userguess = input.nextInt();
        }
        catch (InputMismatchException e)
        {
            System.out.println("Please enter a valid number!");
            input.nextLine();
        }

        if (userguess > numberOfUser)
        {
            System.out.println("Oh man, at the beginning you said that the highest number is: " + numberOfUser);
        }
        else
        {
            if (userguess < 0)
            {
                System.out.println("My number is always taller than 0");
            }
            else
            {
                if (guessNumber < userguess)
                {
                    System.out.println("lower");
                    counter++;
                }
                if (guessNumber > userguess)
                {
                    System.out.println("higher");
                    counter++;
                }
                if (userguess == guessNumber)
                {
                    counter++;
                    break;
                }
            }
        }
    } while (true);

    // </editor-fold>

    // <editor-fold desc="print final result">

    System.out.println(
            "You guessed my number! My number was: " + guessNumber + "! You needed " + counter + " attempts!");

    // </editor-fold>
}
陆啸
2023-03-14

try/catch块中添加input.nextLine()。
调用Scanner.nextLine在每个Scanner.nextInt之后调用以使用该行的其余部分,包括换行符。

 package gessinggame;

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

public class GessingGame {

    public static void main(String[] args) {




//<editor-fold desc="Start Variables and Objects">

        Random random = new Random();
        Scanner input = new Scanner(System.in);

        int counter = 0;
        int numberOfUser = 0;
        int guessNumber = 0;
        int x = 1;
        System.out.print("Try to guess my number! What should be the highest number I can go up to?: ");
        do{
        try{
            numberOfUser = input.nextInt();
            guessNumber = random.nextInt(numberOfUser);
            x = 2;
        }catch(Exception e)
        {
            System.out.print("That doesn't work! Please enter an integer higher than 0 :");
            input.nextLine();
            x = 1;
        }
        }while(x == 1);


        System.out.println("Try to guess my number! Its from 0 to " + numberOfUser + " !");
        System.out.println("---------------------------------------------------");

        do{

                int userguess = input.nextInt();

                    if(userguess > numberOfUser)
                    {
                    System.out.println("Oh man, at the beginning you said that the highest number is: " + numberOfUser);
                    }
                    else{       
                            if(userguess < 0)
                            {
                            System.out.println("My number is always taller than 0");
                            } else{  
                                    if(guessNumber < userguess)
                                    {
                                        System.out.println("lower");
                                        counter++;
                                    }
                                    if(guessNumber > userguess) 
                                    {
                                        System.out.println("higher");
                                        counter++;
                                    }
                                    if(userguess == guessNumber) 
                                    {
                                        counter++;
                                        break;
                                    }
                                    }
                        }
            }while(true);
        System.out.println("You guessed my number! My number was: " + guessNumber + "! You needed " + counter + " attempts!");
    }

}
 类似资料:
  • 对于作业,我必须编写以下代码: 当我尝试编译它时,它在命令提示符下给了我3个错误,说“无法解析符号,符号:类扫描仪,位置:类单词,扫描仪用户输入=新扫描仪(System.in)”。我不确定错误在哪里。我应该使用BufferedReader作为输入吗?

  • 我开发了一个字符排序器,我想每次字符串排序后提示用户输入一个新的字符串。我遇到的问题是扫描仪一直在扫描用户的第一个输入。如果我使用scanner.next(),它不会计算输入末尾的空白,这不是解决方案。 这是while循环的开始。一旦代码完成,它将再次从“inputtext”开始。

  • Player类如下所示: 前面的main方法(它使用多个扫描器,包括try-with-recours,没有任何错误或异常)如下所示:

  • 问题内容: 我有两个Java类,一个包含getter和setter,另一个是驱动程序类。我需要来自驱动程序类中扫描程序的用户输入才能属于第一类中的getter。用户输入必须为double,因为它将用作getter中的公式。 问题答案: 真正最好的是将所有内容都放在一个类中,没有理由将一个类分成两个类,只是为了使获取器和设置器与其他类分开,这 没有任何意义 。我确实想知道您是否误解了您的作业。 现在

  • 问题内容: 我是Java的新手学生,正在尝试完成一个使用扫描仪输入5个学生姓名的程序,然后在其中进行循环以为每个学生获得3个成绩。我一直卡在输入错误匹配错误,我不知道为什么。我试图正确匹配将哪些类型的输入输入到变量中。任何帮助将不胜感激! 这就是我所拥有的: 这就是我得到的: 问题答案: 您的问题在第20行。 这意味着在输入中,它期望一个int值,但它会发现另一件事,例如double,char数组

  • 问题内容: 我正在尝试让扫描仪在循环中进行输入。一旦用户想要完成操作,他就可以退出此循环。我尝试了许多不同的方法来执行此操作,但始终存在一些问题。这是代码: 上面代码的问题(在我尝试的其他方法上也会发生)是,当用户键入 Y时 ,将跳过名字的第一个输入,并跳转到姓氏。如果用户键入 N, 则循环将正确停止。有人可以解释发生这种情况的原因,以及如何克服使用课堂的问题? ps:执行类似的操作,将导致循环终