我正在用java编写一个程序,它一切都很好,直到我想做一个像这样的while循环:
while(String.notEqual(Something)){...}
我知道没有像 notEqual 这样的东西,但有类似的东西吗?
使用 !句法。例如
if (!"ABC".equals("XYZ"))
{
// do something
}
.equals
与 not 运算符结合使用!
。来自JLS §15.15.6,
一元运算符的操作数表达式的类型
!
必须是boolean
orBoolean
,否则会发生编译时错误。一元逻辑补码表达式的类型是
boolean
。在运行时,如有必要,操作数会进行拆箱转换(第 5.1.8 节)。一元逻辑补码表达式的值是
true
如果(可能转换的)操作数值为false
,并且false
(可能转换的)操作数值为true
。
String a = "hello";
String b = "nothello";
while(!a.equals(b)){...}
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...
}
如果您想要区分大小写的比较使用equals()
,否则您可以使用equalsIgnoreCase()
.
String s1 = "a";
String s2 = "A";
s1.equals(s2); // false
if(!s1.equals(s2)){
// do something
}
s1.equalsIgnoreCase(s2); // true
在某些情况下(例如排序)有用的字符串比较的另一种方法是使用compareTo
which0
如果字符串相等,> 0
如果 s1 > s2< 0
否则返回
if(s1.compareTo(s2) != 0){ // not equal
}
还有compareToIgnoreCase
while(!string.equals(Something))
{
// Do some stuffs
}
没有这样的东西叫做 notEquals 所以如果你想否定使用!
while(!"something".equals(yourString){
//do something
}
如果您在循环中更改了字符串,最好考虑 NULL 条件。
while(something != null && !"constString".equals(something)){
//todo...
}