【发布时间】:2016-06-20 05:59:30
【问题描述】:
我不希望用户输入负值。如何检测负值以及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);
【问题讨论】:
-
负数不是
Scanner抛出的异常,所以不能将它添加到catch块中 -
你能发布你的整个代码吗?
标签: java