blah
blah

Reputation: 89

java lexicographically sort three words

I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.

public class SortWords {

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);

    String firstWord;
    String secondWord;
    String thirdWord;


    System.out.println("Enter three words seperated by white space");

    firstWord = userInput.next();
    System.out.println(firstWord);

    secondWord = userInput.next();
    System.out.println(secondWord);

    thirdWord = userInput.next();
    System.out.println(thirdWord);

}

}

Upvotes: 0

Views: 2169

Answers (2)

PSR
PSR

Reputation: 40338

Then try to read as an array elements then sort that array

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    String[] strings = new String[3];

    for (int i = 0; i < strings .length; i++)
    {
        System.out.println("Please enter name");
        strings [i] = input.next();
    }
}

Arrays.sort(strings);

Upvotes: 3

Patashu
Patashu

Reputation: 21793

"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."

This is incorrect.

First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)

Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.

You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.

Upvotes: 1

Related Questions