繁体   English   中英

如何提示用户输入无效并恢复值?

[英]How do i reprompt invalid user input and restore the value?

谁能解释为什么while循环两次问“ NightNight”? 以及如果用户输入的内容不是“ 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);
}

如果您不懂,请告诉我,我会解释!

暂无
暂无

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

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