如何提示用户输入0到100之间的数字?

尝试以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之间。当用户响应第二个提示(由第二个while循环启动)输入一个非int值时,就会出现问题。下面是一个示例:

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()目的。如果输入有效内容,则该循环退出。

以上是 如何提示用户输入0到100之间的数字? 的全部内容, 来源链接: utcz.com/qa/425672.html

回到顶部