Find the alphabetically first String using Java

Viewed 109

My professor asked me to create a solution for this code, and I cannot quite get a good output. He asked me a couple things:

  1. Ask the user to input a String value, the value "END", terminates the loop and the program and is not included in the calculation of Strings.

  2. In the end, you should output which of the Strings that the user inputted is the String that comes alphabetically first. So for ex: if the user inputs "aac" and "aab", the "aab" comes first.

  3. I have created the code, but at the end of the output it gives me the value "END" as the first alphabetically String for some reason, and I am kind of confused.

I do not know if the professor asked right or is it just me that doesn't understand it!

My code so far:

import java.util.Scanner;

public class Ush1_NOTDONE {
    public static void main(String[]args) {
        Scanner sc =  new Scanner(System.in);
        System.out.println("Type a String value, the value \"END\" terminates the code");
        String word = sc.nextLine();

        final String SENTINEL = "END";

        String firstString = null;
        do {
            if(!word.equals(SENTINEL)) {
                System.out.println("Type a String value, the value \"END\" terminates the code");
                word = sc.nextLine();

                if(firstString == null || word.compareTo(firstString)<0 ){
                    firstString = word;
            }

        }}while(!(word.equals(SENTINEL)));

        System.out.println("First alphabetically string is: " + firstString);
        
    }

}
1 Answers

Try to avoid do-while for this. Instead, do assignment in the while condition (assignment in java returns a value).

public class HelloWorld{

     public static void main(String []args){
        String word;
        Scanner sc = new Scanner(System.in);
        String first = null;
        
        while(!(word = sc.nextLine()).equals("END")) {
            if(first == null || word.compareTo(first) < 0) {
                first = word;
            }
        }
        
        System.out.println(first);
     }
}
Related