英文:
Inputting a string into my code that an int is required and I get a java error how can I fix this?
问题
当我错误地将一个字符串输入到下面的代码中进行测试时,控制台会显示一个红色的Java错误消息。然而,在我的if语句中,我添加了一个else部分,如果用户没有输入if语句的条件,即输入0-100之间的数字,程序应该终止。为什么会出现这种情况,我该如何解决?
Scanner input = new Scanner(System.in);
System.out.println("请输入一个数字:");
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//代码
}
else {
System.exit(0);
}
英文:
When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn't input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
答案1
得分: 1
nextInt
方法在输入不是整数时会抛出异常。如果您想要防止这种情况,只需在读取之前使用方法hasNextInt
进行检查。
英文:
The nextInt
method throws an exception if the input is not an integer. If you want to prevent this, just use the method hasNextInt
to check before read it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论