Home > database >  Trying to compare two words in alphabetical order using a while loop to see which one if guess comes
Trying to compare two words in alphabetical order using a while loop to see which one if guess comes

Time:04-23

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!"); 

CodePudding user response:

s1.compareTo(s2) is

  • positive(>0) if s1 comes after s2,
  • negative(<0) if s1 comes before s2,
  • zero (0) if s1 and s2 coincide

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

  • Related