Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading