2013-03-23 50 views
-1

我几乎完成了这个程序,我只是无法验证输入。我需要确保用户只使用AB,CD作为答案,但是当我这样做时,我的程序会重复最终结果并且不会显示"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); 
      } 
     }  
}   
} 
+1

请请请只发布的相关代码(我想没有人会开始计算行找到你所需要的帮助与..) – ddmps 2013-03-23 19:14:12

+0

对不起, – user2079651 2013-03-23 19:17:47

+1

怎么样,使它组合框? – 2013-03-23 19:22:16

回答

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


     } 
+0

计划工作感谢 – user2079651 2013-03-23 21:07:50

+0

欢迎:) – 2013-03-24 03:11:37