如何重复无效的用户输入并恢复值



任何人都可以解释为什么while循环问一夜两次?以及如何在用户输入" 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;
    }

要回答您的问题,我建议您作为第一步调试您的价值观,例如

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);
}

如果您不了解某事让我知道,我将解释!

最新更新