[英]How to reprompt for invalid Boolean input (java)
当我运行程序时,如果键入的不是“ true”或“ false”,它会引发InputMismatchException。
do {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
bus.setIndividualVideo(hasVideo);
} while (!(hasVideo == true) && !(hasVideo == false));
捕获错误并将其视为无效响应...
try {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
} catch (InputMismatchException exp) {
System.err.println("Please, enter only true or false");
}
看看The try Block了解更多详细信息
啊哈,是时候了解Exception
处理了! 实际上,在Java崩溃时看到的任何Exception
类型都可以通过try-catch
块捕获到程序内部。
try {
// code that might throw exceptions 1
// code that might throw exceptions 2
} catch (Exception e) {
// do something to fix the error
}
如果try{ }
部分中的任何代码确实引发了Exception
那么它将立即跳到catch( ) { }
部分,并跳过try{ }
中的任何其他语句。
带有try-catch
代码如下所示:
boolean loopAgain = false;
do {
try {
System.out.print("Do passengers have an individual tv screen?"
+ "(true OR false): ");
hasVideo = keyboard.nextBoolean();
bus.setIndividualVideo(hasVideo);
loopAgain = false;
} catch (InputMismatchException e) {
System.err.println("Please, enter only true or false");
loopAgain = true;
}
} while (loopAgain);
编辑:我借用了println("Please, enter only true or false");
来自@MadProgrammer的答案。
您必须提示用户输入一个布尔值。 因为nextBoolean()
可以引发异常,所以最好的办法是将代码放在try / catch中。 仅在输入true或false以外的任何内容时才执行catch块代码。 您可以添加while()
或do/while()
循环以不断告诉用户重试。 但是,在catch
块中最重要的事情是刷新输入流。 请记住,即使有异常,流中仍然包含内容。 在再次使用之前,必须正确食用它。 下面的代码应完全符合您的期望:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Boolean answer = null;
do
{
System.out.println("Enter either true or false");
try
{
answer = input.nextBoolean();
}
catch(InputMismatchException e)
{
System.out.println("ERROR: The input provided is not a valid boolean value. Try again...");
input.next(); // flush the stream
}
} while(answer == null);
input.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.