我不希望用户输入负值。如何检测负值以及InputMismatchException
?这是我到目前为止的代码!代码似乎不正常,无法找出问题所在。我想验证用户输入以确保负数,字符串和双精度无效并提示用户输入正确的数字,该数字应为正整数。
do {
try {
System.out.println("How many " + teaName + " did you today?");
if(input.hasNextInt() && (numberItem = input.nextInt()) > 0) {
istrue = false;
numberItem = input.nextInt();
}
} catch (InputMismatchException e) {
input.nextLine();
System.out.println("Please enter right number");
istrue = true;
}
catch (NoSuchElementException e){
System.out.println(" Please enter positive integers");
}
} while (istrue);
答案 0 :(得分:0)
do {
try {
System.out.println("How many " + teaName + " did you today?");
if(input.hasNextInt()) {
if (numberItem = input.nextInt()) > 0) {
istrue = false;
numberItem = input.nextInt();
} else {
throw new InputMisMatchException("negative num");
}
}
} catch (InputMismatchException e) {
input.nextLine();
System.out.println("Please enter right number");
istrue = true;
}
catch (NoSuchElementException e){
System.out.println(" Please enter positive integers");
}
}while (istrue);
这应该可行,我所做的就是在数字为负数时抛出一个InputMismatchException。