尝试使用 while 循环按字母顺序比较两个单词,以查看如果猜测出现在单词之前或之后的单词

Trying to compare two words in alphabetical order using a while loop to see which one if guess comes before of after word

我正在尝试比较两个词,看看猜测是否出现在使用 compareTo()

的词之前
while(!guess.equals(word)){
    if(compare < 0){
        System.out.println(word + " Comes before your guess. ");
        detail(); 
    } else if(compare > 0) {
        System.out.println(word + "Comes after your guess. "); 
        detail(); 
    }
}
System.out.println("You guessed it!"); 

s1.compareTo(s2)

  • positive(>0) if s1 comes after s2,
  • negative(<0) 如果 s1 出现在 s2,
  • 之前
  • 零 (0) 如果 s1s2 重合

所以,在你的情况下你应该

    if(word.compareTo(guess) < 0){
        System.out.println(word + " Comes before your guess. ");
        detail(); 
    } else if(word.compareTo(guess) > 0) {
        System.out.println(word + "Comes after your guess. "); 
        detail(); 
    }