2011-06-22 43 views
-1
public void play() { 
    int anInteger; 
    //guess return code 
    int code; 

    while (true) { 
     String input=null; 
     input = JOptionPane.showInputDialog("Please enter an integer"); 

     if (input == "-1") { 
      //JOptionPane.showMessageDialog(null, input); 
      System.exit(0); 
      break; 
     } else { 
      if (input==null) { 
       System.exit(0); 
      } else if (input.isEmpty()) { 
       continue; 
      } else { 
       anInteger = Integer.parseInt(input); 
       code = this.oneGuess (anInteger); 
       //JOptionPane.showMessageDialog(null, anInteger); 
      } 
     } 

    } 
} 

我想,如果用户输入-1,显示程序不会再提示消息框。以上是迄今为止我所提出的代码。为什么它不起作用?不能打破while循环

+2

您正在等待您的代码中输入“1”来打破循环,而不是“-1” – evilone

+0

输入错误............ – hkvega

+1

我还建议您使用适合de的IDE发展(日食,netbeans等)cos编写==而不是.equals()shd向你显示警告,你可以纠正你自己。 –

回答

5

您正在将字符串(它们是对象)与==运算符进行比较,该运算符检查两个对象引用是否引用同一个对象实例。相反,您应该使用equals方法进行比较。

0

==equals相比,有所不同。第一个比较指针,后者的内容。这可能是你的问题。

-1

您将字符串与==比较,这会产生问题。你可以有许多不同的字符串对象,都显示“-1”。 ==测试,如果你在左侧和右侧有完全相同的对象。你想知道,如果左边和右边的对象有相同的内容。

最好尝试

input.equalsIgnoreCase("-1"); 

编辑:要回答的评论:input.equalsIgnoreCase( “ - 1”)是一样的input.equals( “ - 1”)的情况下, “-1”因为“-1”中没有大写/小写字母。不过,在字符串的情况下,我更喜欢equalsIgnoreCase,因为它是在String上定义的,而不是在Object上定义的。尽管如此,由于String类的equals-definition被覆盖,所以在这个例子中它也起作用,并且不需要“ignoreCase”。

+0

你可能想添加一个'input.equalsIgnoreCase(“ - 1”)'和'input.equals(“ - 1”)'不一样的例子。 ;) –

7

字符串比较不符合 “==” 运营商合作,使用 “String.equals(对象)” 功能

input.equals("-1"); 

更好的方式是

"-1".equals(input); 

,因为它也需要照顾空输入

+0

+1为转过来,包括检查为空 –

+0

+1,优秀的答案。欢迎来到Stack Overflow。 :) – Mikaveli