6

我正在用java编写一个程序,它一切都很好,直到我想做一个像这样的while循环:

while(String.notEqual(Something)){...}

我知道没有像 notEqual 这样的东西,但有类似的东西吗?

4

8 回答 8

18

使用 !句法。例如

if (!"ABC".equals("XYZ"))
{
// do something
}
于 2013-02-07T03:02:30.797 回答
3

.equals与 not 运算符结合使用!。来自JLS §15.15.6

一元运算符的操作数表达式的类型!必须是 booleanor Boolean,否则会发生编译时错误。

一元逻辑补码表达式的类型是boolean

在运行时,如有必要,操作数会进行拆箱转换(第 5.1.8 节)。一元逻辑补码表达式的值是 true如果(可能转换的)操作数值为false,并且false(可能转换的)操作数值为true

于 2013-02-07T03:02:41.450 回答
2
String a = "hello";
String b = "nothello";
while(!a.equals(b)){...}
于 2013-02-07T03:03:46.307 回答
1
String text1 = new String("foo");
String text2 = new String("foo");

while(text1.equals(text2)==false)//Comparing with logical no
{
   //Other stuff...
}

while(!text1.equals(text2))//Negate the original statement
{
   //Other stuff...
}
于 2013-02-07T03:03:57.573 回答
1

如果您想要区分大小写的比较使用equals(),否则您可以使用equalsIgnoreCase().

String s1 = "a";
String s2 = "A";

s1.equals(s2); // false

if(!s1.equals(s2)){
  // do something
}

s1.equalsIgnoreCase(s2); // true

在某些情况下(例如排序)有用的字符串比较的另一种方法是使用compareTowhich0如果字符串相等,> 0如果 s1 > s2< 0否则返回

if(s1.compareTo(s2) != 0){ // not equal

}

还有compareToIgnoreCase

于 2013-02-07T03:32:48.100 回答
0
while(!string.equals(Something))
{
   // Do some stuffs
}
于 2013-02-07T03:02:41.973 回答
0

没有这样的东西叫做 notEquals 所以如果你想否定使用!

while(!"something".equals(yourString){
//do something
}
于 2013-02-07T03:08:23.400 回答
0

如果您在循环中更改了字符串,最好考虑 NULL 条件。

while(something != null && !"constString".equals(something)){
     //todo...
}
于 2013-02-07T08:45:56.407 回答