我正在编写一个程序,其中包括测试用户输入是否为正整数,如果条目是非整数或负数,则显示错误消息。如果输入非整数,我的代码会显示预期的错误消息,但如果输入负整数,则仅重新提示输入正整数。我尝试过添加:
if (n <= 0);
System.out.print("You have not entered a positive integer");
前
n = input.nextInt();
但即使输入正整数,也会出现错误消息。
我也尝试过:
while (!input.hasNextInt() && n <= 0)
感谢任何帮助。
Scanner input = new Scanner( System.in );
int n = 0;
do {
System.out.print("Please enter a positive integer: ");
while (!input.hasNextInt()){
System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: ");
input.next();
}
n = input.nextInt();
} while (n <= 0);
答案 0 :(得分:1)
试试这个:
int n = -1;//<-- it won't allow user to skip the loop after first pass without proper input
do {
System.out.print("Please enter a positive integer: ");
try {
n = input.nextInt();//<-- in one pass ask input from user only once
if(0 > n) {
System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: ");
}
} catch (NumberFormatException ex) {
System.out.println("Invalid number !");
break;//<-- break loop here, if don't wana prompt user for next input
} catch(java.util.InputMismatchException ex) {
System.out.println("Oops number is required !");
break;//<-- break loop here, if don't wana prompt user for next input
}
} while (n <= 0);
答案 1 :(得分:0)
试试这个:
int n = -1;
while (input.hasNextInt() && (n = input.nextInt()) < 0)
{
// print error message about negative number
}
当循环退出时,如果&#39; n&#39;仍然是-1你到输入结束,例如用户输入ctrl / d或ctrl / z,具体取决于平台。
如果用户在控制台,您可能还需要跳到行尾。