本文介绍了在Java中输入无效后重新提示用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Java编写此程序,我需要在输入无效后重新提示用户.我来到一个解决方案,只是发现如果用户在重新提示后输入另一个无效输入,则它将继续.有人可以告诉我更好的解决方案吗?无论如何,我都会告诉你:
I'm writing this program in java where I need to re-prompt the user after an invalid input. I came to a solution only to discover that if the user enters another invalid input after the re-prompt then it continues. Can someone please show me a better solution to this? I'll show you what I had anyway:
System.out.println("What is your age?\n");
age = userInput.nextInt();
if((age > 120) || (age < 1)) {//error message
System.out.println("ERROR Please enter a valid age");
System.out.println("");
System.out.println("What is your age?\n");
age = userInput.nextInt();
}//end if
如果用户在再次被提示后输入了无效的输入,程序将继续运行,我该如何克服呢?
if the user entered an invalid input after they were prompted again, the program would just continue, how can I overcome this?
推荐答案
将if
替换为while
.
BAM,问题已解决.
BAM, problem solved.
这篇关于在Java中输入无效后重新提示用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!