简体   繁体   English

如何使用do-while循环来捕获用户?

[英]How to trap user with do-while loop?

String error = "Write a number below, between 1-9;";
int number;
do {
    String userentered = JOptionPane.showInputDialog(error);
    number = Integer.parseInt(userentered);
    if (number < 0 && number > 10) {
        error = "Error";
    }
} while (number > 0 && number < 10);

I want to trap the user in this do while loop, until there have provided the correct answer, eg number between 1-9, right now. 我想在这个do while循环中捕获用户,直到提供了正确的答案,例如1-9之间的数字,现在。 Right now, when the user types in a letter or leaves the field black and click ok, the optionpane closes but I want it to stay open until the correct input is given. 现在,当用户键入一个字母或将字段留空并单击“确定”时,选项窗格会关闭,但我希望它保持打开状态,直到给出正确的输入。 Right now, also if the user types in the correct input it gives them the error message but if there type in a wrong input it closes. 现在,如果用户键入正确的输入,它也会给出错误消息,但如果键入错误的输入则会关闭。

You need to change the while condition of the do-while loop. 您需要更改do-while循环的while条件。 Currently it is looping if the number is within the range, but your requirement is the exact reverse of it. 目前,如果数字在该范围内,它将循环,但您的要求与其完全相反。

while (!(number > 0 && number < 10)); // Keep looping if the number is outside the range.

Note: The Integer.parseInt() will throw a java.lang.NumberFormatException if the improper inputs are not handled properly. 注意:如果未正确处理不正确的输入, Integer.parseInt()将抛出java.lang.NumberFormatException

It's Simple, do while loop is entry control loop. 它很简单,while循环是入口控制循环。 so we need to stat from one less value. 所以我们需要从一个较少的值来统计。

            String errorMsg = "Write a number below, between 1-9;";
    int number = 0;
    do {
        try {
            String usernum = JOptionPane.showInputDialog(errorMsg);
            number = Integer.parseInt(usernum);
            if (number < 1 || number > 9) {
                errorMsg = "Error";
            }
        } catch (Exception e) {
            errorMsg = "Error";
        }
    } while (number < 1 || number > 9);

You have to add the parseInt method in try-catch block. 您必须在try-catch块中添加parseInt方法。 Also modify the condition to be number < 1 || 同时将条件修改为数字<1 || number > 9. finally you have to initialize the number with invalid value, lets say -1 number> 9.最后你必须使用无效值初始化数字,让我们说-1

String error = "Write a number below, between 1-9;";
int number = -1;
do {
    try {
        String userentered = JOptionPane.showInputDialog(error);
        number = Integer.parseInt(userentered);
        if (number < 1 || number > 9) {
            error = "Error";
        }
    } catch (HeadlessException | NumberFormatException e) {
        error = "Error";
    }
} while (number < 1 || number > 9);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM