我正在编写一个程序,其中包含一个测试,以确定用户输入是否为正整数,并在条目为非整数或负数时显示错误消息。如果输入非整数,我的代码将显示预期的错误消息,但只有在输入负整数时才会再次提示输入正整数。我试着添加:使用具有do-while循环的hasNextInt,没有负整数的错误消息
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);
异常是太大的例外在这里使用,只是使用NumberFormatException。 –
我试过这个,当输入一个非整数时会得到一个无限循环。 –
@Arvind,谢谢!这工作! –