有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数据验证执行while循环

我在验证字符串输入时遇到问题。我想使用户不能输入无效字符串(仅限“CIS 280”、“ACC 201”、“CIS 120”、“CIS 185”)。然而,我不知道如何用字符串来实现它

我的问题是

  1. 当我输入有效输入时,程序退出,不显示相应的时间
  2. 当我在第一个输入对话框中输入无效输入时,程序随后进入无限循环,即使我在以下位置输入有效字符串:

    invalid = JOptionPane.showInputDialog("Please enter a valid class.");
    
public class arraytest {
    public static void main(String[] args) {
        int i = 0;
        String classInput;
        boolean valid = false;
        String invalid;
        String[][] classNames = {
          {"CIS 280", "ACC 201", "CIS 120", "CIS 185"},
          {"Tue 5:00", "Mon & Weds 12:20", "Mon & Weds 10:10", "Mon & Weds 12:00" }
        };
        classInput = JOptionPane.showInputDialog("Please input a class name: ");

        do {
            for (i = 0; i < classNames[0].length; ++i) {
                if(classNames[0][i].equals(classInput)) {
                    valid = true;
                }
            }
            if(valid == false) {
                invalid = JOptionPane.showInputDialog("Please enter a valid class.");
                classInput.equals(invalid);
            }
        } while(valid == false);

        JOptionPane.showMessageDialog(null, "The time of that class is: " + classNames[1][i]);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    而不是

    get users input
    do{
       validate input
       if input is wrong ask again //btw here is your error, 
                                   //check where you are storing user's input
    }while(input is wrong)
    

    试试看

    do{
       get users input
       validate input
    }while(input is wrong)
    

    另一件事是迭代到行的末尾,这将使i等于行的length。当你找到正确的值时,你需要停止迭代,这样你就可以在你的应用程序中使用这个i

    JOptionPane.showMessageDialog(null, "The time of that class is: " + classNames[1][i]);