在 Java 中输入无效后重新提示用户 [英] Re-prompt user after invalid input in Java

查看:17
本文介绍了在 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?
");
    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?
");
        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?

推荐答案

while 替换 if.

BAM,问题解决了.

这篇关于在 Java 中输入无效后重新提示用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆