2013-02-27 65 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. 转到第一步