首页 > 解决方案 > 如何做出异常通知用户他们输入的数字超出范围?

问题描述

我的老师给了我们一个任务,要求用户输入 1 到 50 的整数,我几乎完成了我的代码,但唯一缺少的是在用户输入超过 50 时通知用户。你能帮助我的代码中缺少什么。我已经阅读了我的讲义,没有限制一定数量的整数或其他任何东西的例外。

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;
    boolean condition = false;

    System.out.println("Guess a Number 1 - 50:");
    
    do {
        condition = true;
        try {
            int input = scan.nextInt();
            scan.nextLine();
            
            if(input > answer) {
                System.out.println("Too Big");
                System.out.println(); //Spacing
                System.out.println("Guess a Number 1 - 50:");
                attempts++;
            } else if (input < answer) {
                System.out.println("Too Small");
                System.out.println(); //Spacing
                System.out.println("Guess a Number 1 - 50:");
                attempts++;
            } else {
                int totalA = attempts + 1;
                System.out.println(); //Spacing
                System.out.println("Congratulations! "+ "You attempted " + totalA + " times." );
            } 
            
        } catch (InputMismatchException e) {
            System.out.println("Numbers only");
            System.out.println(); //Spacing
            System.out.println("Guess a Number 1 - 50:");
            condition = true;
            scan.nextLine();
        } 
        
    } while(condition);



}

标签: java

解决方案


我认为非常重要的是,您知道您可以创建自己的Exception具有特定消息和用途的类。

例如:

public class NumberTooHighException extends Exception { 
    public NumberTooHighException() {
        super("The number inputted is wayyyy to high...");
    }
}

然后你可以使用你Exception的任何其他:

if(input > 50)
{
    throw new NumberTooHighException(); // Here you throw it...
}

如果你想要catch它,你可以将你的代码包装在一个try-catch块中。更多关于这里

但正如评论暗示的那样:

异常是一种让方法告诉该方法的调用者出现问题的方法

所以尽量避免将它们用于特定的用例(例如这个)。即使您的作业是家庭作业/学校作业。


推荐阅读