2013-02-27 70 views
0
String inputRules = JOptionPane.showInputDialog 
    (
    "Enter your rules. \n" + 
    "In the form: a=x" 
); 

    boolean gotGoodRuleInput = false; 

    while (!gotGoodRuleInput) 
    { 
     gotGoodRuleInput = true; 

     char a = inputRules.charAt(0); 

     for (int i= 2; i<inputRules.length(); i++) 
     { 
     char x = inputRules.charAt(i); 
     if (a == x) 
     { 
     JOptionPane.showMessageDialog 
     ( 
      null, 
      "a can not equal x", 
      "Error", 
      JOptionPane.ERROR_MESSAGE 
     ); 
     gotGoodRuleInput = false; 
     } 
     } 
    } 

你好我試圖檢查用戶輸入,如果輸入在x等於a那麼它會給出錯誤對話框。我遇到的問題是,錯誤對話框「一個不能等於x」會一直出現,並在打好時不會關閉。我認爲它與for循環有關,但我無法弄清楚。循環錯誤消息

+0

我沒有看到你在做什麼。我相信一個更好的方法是使用String類中的split方法來分隔'='符號部分和'='符號部分之後的部分。 – pattmorter 2013-02-27 04:52:37

+0

嗯我不知道這件事,我認爲它更好地工作,謝謝你的提示。 – Mert 2013-02-27 05:04:54

回答

1

inputRules的設置在循環之外,所以一旦出現錯誤情況,您將永遠無法擺脫它。

+0

謝謝,完全解決了我的問題 – Mert 2013-02-27 05:19:51

0

就像John說的那樣,inputRules在循環之外,所以什麼都不會改變。不知道這是否是你想要完成的,但是如果你可以用這個替換循環。

String[] input = inputRules.split("="); 
if (input[0].equals(intput[1])) { 
    JOptionPane.showMessageDialog 
    ( 
     null, 
     "a equals x" 
    ); 
    gotGoodRuleInput = true; 
} else { 
    JOptionPane.showMessageDialog 
    ( 
     null, 
     "a can not equal x", 
     "Error", 
     JOptionPane.ERROR_MESSAGE 
    ); 
    gotGoodRuleInput = false; 
} 
+0

謝謝我不知道分裂,但它似乎非常有用 – Mert 2013-02-27 05:10:06

1

問題的邏輯,在邏輯 看

while (!gotGoodRuleInput) 
    { 

...

,如果錯誤

gotGoodRuleInput = false; 

正在發生的事情:

  1. 檢查而conditon
  2. 成立,而條件爲假
  3. 通過所有輸入讀取
  4. 循環值
  5. 檢查codition
  6. 顯示對話框
  7. 如果上述條件屬實,成立而條件變爲真
  8. 轉到第一步