2013-03-23 45 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