如何重新提示无效的用户输入并恢复该值?

时间:2017-10-05 05:35:50

标签: java

有人可以解释为什么while循环会问whatNight两次吗?以及如果用户输入“r”或“c”以外的其他内容,如何重新提示无效的用户输入

    for(int x = 1; x <= inputInt; x++) {
    char whatNight  = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    boolean pleasework = whatNight == 'c' || whatNight == 'C';
    boolean imbeggingu = whatNight == 'r' || whatNight == 'R';
    boolean doesNotWork = whatNight != 'c' && whatNight != 'C' && whatNight != 'r' && whatNight != 'R';

    //why does the while loop ask twice even if u enter c or r?
    while(pleasework || imbeggingu || doesNotWork) {

        if(doesNotWork) 
            JOptionPane.showMessageDialog(null, "INvalid letter");
             whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
        //reprompt not storing in whatNight variable :/

             if(pleasework)  
            JOptionPane.showMessageDialog(null, "You entered c for carnight");

             else if(imbeggingu)  
            JOptionPane.showMessageDialog(null, "You entered r for regular night");
            break;
    }

1 个答案:

答案 0 :(得分:0)

要回答您的问题,我建议您首先调试您的值,例如

System.out.println(pleasework);

你的概念逻辑很不错,你应该重新考虑如何处理这个问题。例如,当你的输入不是C或R时,你要求一个新的输入,但你不要根据它设置任何布尔值。

这应该有用!

for(int x = 1; x <= inputInt; x++) {
    char whatNight  = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0); 
    whatNight = checkInput(whatNight);
    boolean nightC = whatNight == 'c' || whatNight == 'C';
    boolean nightR = whatNight == 'r' || whatNight == 'R';

    if(nightC) {
        JOptionPane.showMessageDialog(null, "You entered c for carnight");
    } else if(nightR) {
        JOptionPane.showMessageDialog(null, "You entered r for regular night");
    }
}

---------------------------------------------------------------------

private char checkInput(char input) {
    if(input == 'c' || input == 'C' || input == 'r' || input == 'R') {
        return input;
    }
    char whatNight = JOptionPane.showInputDialog("You entered a wrong letter, enter either c or r for what type of night it was").charAt(0);
    return checkInput(whatNight);
}

如果您不明白某事,请告诉我,我会解释!