java - 如何做出异常通知用户他们输入的数字超出范围?
问题描述
我的老师给了我们一个任务,要求用户输入 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);
}
解决方案
我认为非常重要的是,您知道您可以创建自己的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
块中。更多关于这里。
但正如评论暗示的那样:
异常是一种让方法告诉该方法的调用者出现问题的方法
所以尽量避免将它们用于特定的用例(例如这个)。即使您的作业是家庭作业/学校作业。
推荐阅读
- android - 有没有一种简单的方法可以将 sqlite db 同步到 firebase json?
- android - Android 不再允许我安装 app-debug
- android - 设备管理员究竟是如何为卸载应用添加一层安全保护的?
- c++ - 如何使用 char* 修复此内存泄漏?
- reactjs - @react-native-community/react-native-device-info:NativeModule.RNDeviceInfo 为空
- c++ - C++中私有继承抽象基类是什么意思
- c++ - 有没有办法在不使用任何迭代的情况下按字母顺序排列字符串中的字符?
- .net - 图表:计算最短 N 条路径,最大连接数为 M
- jquery - 如何使用 Jquery 获取 HTML 标签的完整定义?
- java - 如何正确构建 REST-API 端点