如何解决循环用户输入直到输入非零正整数
我是一个完整的初学者,我正在尝试创建一个 while 循环,该循环不断询问用户输入,直到它得到一个正的非零整数,然后继续进行下一部分。这是我到目前为止所得到的:
System.out.println("Enter the speed of the vehicle in "
+ "miles per hour: ");
while (keyboard.hasNext())
{
if (keyboard.hasNextInt())
{
speed = keyboard.nextInt();
while (speed <= 0)
{
System.out.println("Please enter a positive nonzero number: ");
speed = keyboard.nextInt();
}
}
else
{
System.out.println("Please enter a number: ");
speed = keyboard.nextInt();
}
}
现在,当我运行它并输入除整数以外的任何内容时,它会打印出“请输入数字”这一行,但随后我立即收到 InputMatchException 错误并且构建失败。如果我输入一个负数或零,它会提示我输入一个正数,直到我输入,但是代码只是停止执行并继续运行而无限期地什么都不做,而不是在循环之后继续执行部分,这只是从另一个系统开始。输出。在此先感谢您的帮助。
解决方法
您需要消耗之前输入的非int
,然后尝试读取以下输入:
else
{
System.out.println("Please enter a number: ");
// consume and ignore the previous non-int input
keyboard.next();
}
,
你可以这样做。通过使用 Scanner#nextLine() 方法请求数值的字符串表示,然后应用带有小 String#matches()(正则表达式)的 Regular Expression 方法来验证提供了正数值的事实( "\\d+"
表达式),例如:
String speedString = "";
while (speedString.isEmpty()) {
System.out.println("Enter the speed of the vehicle in miles per hour: ");
speedString = keyboard.nextLine().trim();
if (!speedString.matches("\\d+") || Integer.valueOf(speedString) < 1) {
System.err.println("Invalid speed value supplied!\n"
+ "Please enter a 'positive' non-zero number.\n");
speedString = "";
}
}
int speed = Integer.parseInt(speedString);
,
对输入不匹配使用 try/catch 和对负值使用验证循环。
import java.util.InputMismatchException;
import java.util.Scanner;
public class BadInputTryCatch {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
boolean isInt = false;
// Validate Integer
do {
try {
// Validate Positive
do{
System.out.print("Enter a positive number --> ");
n = scan.nextInt();
}while(n < 0);
isInt = true;
System.out.println(n + " is positive!");
// Catch NOT integer
} catch (InputMismatchException ex) {
System.out.println("I said an I N T E G E R ...)");
scan.nextLine(); // discard input (Clear buffer)
}
} while (!isInt);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。