-1

结果必须是大于单词“END”的字符串。这是我到目前为止所做的,但它只是不起作用。

System.out.println("Write a word. The word "END" terminates the program");

String word = sc.nextLine();

if(word.equals("END")){
    System.out.println("Nothing has been typed");
}

while(word!="END"){
    if(word.compareTo("END") > 0){
        System.out.println(word+" is greater than END");
    }
}
4

3 回答 3

1

您的词典比较(即哪个单词按字母顺序较早)是正确的。但是,您的循环条件不正确:

while(word!="END")

永远都是真的。你应该把它改成

while(!"END".equals(word))

在这种情况下,循环将在到达 word 时停止END

如果您想要不区分大小写的比较,请使用compareToIgnoreCase而不是compareTo,而equalsIgnoreCase不是equals

于 2013-02-26T16:32:00.620 回答
0
while(word!="END") is always true because it check object reference .You should try
while(!"END".equals(word)) where object content is checked
于 2013-02-27T15:17:36.350 回答
0

while(!"END".equals(word))您的循环条件不正确

于 2015-02-19T17:06:52.427 回答