[英]Java help exception handling
public static void main(String[] args) {
int age=0 ;
while(age == 0) {
System.out.println("How old are you");
age = checkValidAge();
}
}
public static int checkValidAge() {
try {
return userInput.nextInt();
}
catch(InputMismatchException e) {
userInput.next();
System.out.println("Enter a interger");
return 0;
}
}
}
Started learning java recently(complete beginner).最近开始学习java(完全初学者)。
So I am bit confused, when I input numbers this cause loop to break and when I enter characters loop dont break so isn't meant to be other way around.所以我有点困惑,当我输入数字时,这会导致循环中断,而当我输入字符时,循环不会中断,所以并不意味着相反。
Just wanted to create something that catches the error and lets you try again.只是想创建一些可以捕获错误并让您重试的东西。
As your code writes:正如您的代码所写:
while (age == 0)
When your your input is当您的输入是
checkValidAge()
return 3 and assign 3 to age
,checkValidAge()
返回 3 并将 3 分配给age
,age = 3
, it will of course break the while loop because a == 0
is false ;age = 3
,它当然会中断 while 循环,因为a == 0
为false ;checkValidAge()
will raise InputMismatchException
, and the checkValidAge()
return value is 0
.checkValidAge()
将引发InputMismatchException
,并且checkValidAge()
返回值为0
。0
is assigned to the local variable age
, which means age = 0
.0
分配给局部变量age
,这意味着age = 0
。 At this time, age == 0
returns true, and meets the requirments for the while loop to continue.age == 0
返回true,满足while循环继续的要求。No, it is the right way around.不,这是正确的方法。 The whole idea of the prompt loop is to get a valid Integer value.
提示循环的整个想法是获取有效的整数值。 If the supplied data is invalid then the User is informed and the 0 is returned from the validation method so that the prompt loop continues and provides the User with the same prompt in order to try again.
如果提供的数据无效,则通知用户并从验证方法返回 0,以便提示循环继续并为用户提供相同的提示以便重试。
Since validation is to be carried out on the User's input then perhaps you should go all the way with it for this particular Age prompt.由于要对用户的输入进行验证,因此对于这个特定的年龄提示,您可能应该一直使用它。 There are a lot of integers that can be supplied which should be considered invalid such as:
有很多可以提供的整数应该被认为是无效的,例如:
You may want to add a inclusive value range to your checkValidAge() method:您可能希望向checkValidAge()方法添加一个包含值范围:
public static int checkValidAge(int min, int max) {
int ageValue = 0;
try {
ageValue = userInput.nextInt();
if (ageValue < min || ageValue > max) {
throw new InputMismatchException();
}
}
catch(InputMismatchException e) {
System.out.println("Invalid age supplied! (" + ageValue + ")");
ageValue = 0;
}
userInput.nextLine(); // consume ENTER
return ageValue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.