尝试将用户输入作为 0 到 100 之间的整数,并提示用户“再试一次”,只要他们的输入不符合此条件。
到目前为止,我的代码在一定程度上成功地实现了我的目标:
import java.util.Scanner;
public class FinalTestGrade
{
public static void main(String[] args)
{
Scanner studentInput = new Scanner (System.in );
int testGrade;
System.out.println("Please enter your test grade (0 to 100)");
while (!studentInput.hasNextInt())
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
studentInput.next();
}
testGrade = studentInput.nextInt();
while (testGrade > 100 || testGrade < 0)
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
testGrade = studentInput.nextInt();
}
如您所见,程序将检查输入是否为 int。一旦用户成功输入一个 int,程序检查以确保他们的输入在 0 到 100 之间。当用户输入一个非 int 作为响应时,问题就出现了 到第二个提示(由第二个 while 循环启动)。下面是一个例子:
run:
Please enter your test grade (0 to 100)
P
Your input does not match the criteria, please enter a number between 0 and 100
109
Your input does not match the criteria, please enter a number between 0 and 100
P
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at finaltestgrade.FinalTestGrade.main(FinalTestGrade.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)
长话短说,我想知道是否有一种方法可以组合我的 while 循环,以便接受表示为 0 到 100 之间的 int 的输入并将其保存为变量。所有不符合此标准的输入都应触发重复提示,直到输入符合此标准。有什么建议吗?
最佳答案
int testGrade = -1 ;
Scanner studentInput = new Scanner(System.in);
while (testGrade > 100 || testGrade < 0)
{
System.out.println("Your input does not match the criteria, please enter a number between 0 and 100");
while(!studentInput.hasNextInt())
{
studentInput.next() ;
}
testGrade = studentInput.nextInt();
}
有一个无限循环来检查流中是否有无效字符。如果是,则使用它,这就是 hasNextInt()
的用途。如果您输入有效内容,该循环就会退出。
关于java - 如何提示用户输入 0 到 100 之间的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13078951/