-1

我几乎完成了这个程序,我只是在验证输入时遇到了麻烦。我需要确保用户只使用ABCD作为答案,但是当我这样做时,我的程序会重复最终结果,而不仅仅是显示"Only A, B, C, and D are valid"窗口。我只需要帮助修复考试类中的第 101-125 行(下面的最后一个代码部分)。

错误在这部分

public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();

if (actionCommand.equals("Exit")){
    System.exit(0);
}
else if (actionCommand.equals("Grade")){
    char[] input = new char[20];
    for (int i= 0; i < input.length; i++){

        input[i] = answerTextFields[i].getText().charAt(0);
        input[i] = Character.toUpperCase(input[i]);
    }
      for (int i=0; i<=input.length; i++) {
            if (input[i] < 'A'|| input[i] > 'D') {
               JOptionPane.showMessageDialog(null, "Only A, B, C, and D are valid");
            } 
            else {
    driver.setName(nameTextField.getText());
    driver.report(input);
            }
      }    
}        
}
4

2 回答 2

0

如果我理解您的问题,您希望一旦警告消息显示在对话框窗口中,该程序就不应重复。如果您不希望程序在显示对话框窗口后重复,我认为您需要中断循环。这是修改后的代码:

for (int i=0; i<=input.length; i++) {
        if (input[i] < 'A'|| input[i] > 'D') {
           JOptionPane.showMessageDialog(null, "Only A, B, C, and D are valid");
           break; // Added to break the loop
        } 
        else {
driver.setName(nameTextField.getText());
driver.report(input);
        }
  }    
于 2013-03-23T19:35:37.303 回答
0

尝试这个:

        String actionCommand = e.getActionCommand();
        boolean checkValidate = true;
        if (actionCommand.equals("Exit")) {
            System.exit(0);
        } else if (actionCommand.equals("Grade")) {
            char[] input = new char[20];
            for (int i = 0; i < input.length; i++) {

                input[i] = answerTextFields[i].getText().charAt(0);
                input[i] = Character.toUpperCase(input[i]);
            }
            for (int i = 0; i <= input.length; i++) {
                if (input[i] < 'A' || input[i] > 'D') {
                    JOptionPane.showMessageDialog(null, "Only A, B, C, and D are valid");
                    checkValidate = false;
                    break;
                }
            }

////////////if the user enter wrong answer , it's no need to print the report , so i make the report out For Loop 

            if (checkValidate) {
                driver.setName(nameTextField.getText());
                driver.report(input);
            }


        }
于 2013-03-23T19:54:41.273 回答