javaperformancemethodscompareto

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


I am trying to compare two words and see if guess comes before word using 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!"); 

Solution

  • s1.compareTo(s2) is

    So, in your case you should

        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(); 
        }