java - 输入验证(do-while 循环)出现故障

标签 java validation input while-loop

===== CS302 TOOL BOX =====
T > COIN TOSS SIMULATOR
G > GRADE ESTIMATOR
C > COLOR CHALLENGE
Q > QUIT
Type code letter for your choices: h
Invalid selection. Please try agian: 
t
Invalid selection. Please try agian: 
T

^这是我运行程序并给出错误猜测时得到的结果。该循环是为了验证用户输入而进行的,因此它完全失败了。关于我做错了什么有什么想法吗?感谢您的宝贵时间!

}

    System.out.println("===== CS302 TOOL BOX =====");
    System.out.println("T > COIN TOSS SIMULATOR");
    System.out.println("G > GRADE ESTIMATOR");
    System.out.println("C > COLOR CHALLENGE");
    System.out.println("Q > QUIT");
    System.out.print("Type code letter for your choices: ");
    boolean code_letter;
    String code_choice = scanner.next();
    do {
        if (code_choice.toUpperCase().equals("Q")
                || (code_choice.toUpperCase()).equals("C")
                || (code_choice.toUpperCase()).equals("G")
                || (code_choice.toUpperCase()).equals("T")) {
            code_letter = true;
        }

        else {
            System.out.println("Invalid selection. Please try agian: ");
            code_letter = false;
            scanner.next();
        }
    } while (!(code_letter));

    {

        System.out.println("you did it?");
    }

}
}

最佳答案

do-while 循环中初始化 code_choice 变量,否则在条件测试之前,该变量将不会在循环的每次迭代中重新初始化.

String code_choice = scanner.next();

像这样

//declared it outside to take care of the scope
String code_choice = null;
    do {
        //initialize it every time before you perform the conditional test.
        //This increases the readability!
        code_choice = scanner.next();
        if (code_choice.toUpperCase().equals("Q")
                || (code_choice.toUpperCase()).equals("C")
                || (code_choice.toUpperCase()).equals("G")
                || (code_choice.toUpperCase()).equals("T")) {
            code_letter = true;
        }

        else {
            System.out.println("Invalid selection. Please try agian: ");
            code_letter = false;
        }
    } while (!(code_letter));

希望这有帮助!

关于java - 输入验证(do-while 循环)出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844025/

相关文章:

java - jsp如何根据jsp页面调用的servlet完成的处理显示附加数据

java - 向 Arraylist 添加值

iphone - 密码文本字段的顺序验证

python - 要求用户提供输入,直到他们给出有效的答复

python - 无法比较 Python 3.2 中的输入字符串

Java SQL 结果集数据类型

java - Java如何知道依赖jar在哪里?

windows - 批处理脚本 : Validate Date Input

c++ - 在 C++ 中读取文本文件

java - 如何检查用户输入而不退出错误