循环错误消息

时间:2013-02-27 04:47:41

标签: java input for-loop

  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,那么它将给出错误对话框。我遇到的问题是错误对话框“a can not equal x”一遍又一遍地出现,并且在点击ok时不会关闭。我认为它与for循环有关,但我无法弄明白。

3 个答案:

答案 0 :(得分:1)

inputRules的设置超出了循环范围,因此一旦出现错误情况,您将永远不会离开它。

答案 1 :(得分:1)

逻辑上的问题,在你的逻辑中 看看

while (!gotGoodRuleInput)
    {

...

如果错误

gotGoodRuleInput = false;

发生了什么:

  1. 同时检查条件
  2. 设置条件为false
  3. 阅读
  4. 循环显示所有输入值
  5. check codition
  6. 显示对话框
  7. 如果上述条件为真,则将条件设置为true
  8. 转到第一步

答案 2 :(得分: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;
}
相关问题