1

I've come across an issue whilst doing some homework. The problem is to take three strings and sort them. I've gotten this down for numbers but I don't know how to accomplish this with strings.

Here it is verbatim from the book:

Write a program that reads three strings and prints them in lexicographically sorted order.

Please enter three strings:
Tom
Dick
Harry
The inputs in sorted order:
Dick
Harry
Tom

My Tester:

package Chapter_5;

import java.util.Scanner;

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

        System.out.println("Please provide three strings:");

        StringOrder str = new StringOrder(in.nextLine(),in.nextLine(),in.nextLine());
    }
}

My Code:

package Chapter_5;

public class StringOrder 
{
    public StringOrder(String str1, String str2, String str3)
    {
        String index;

        int i = str1.compareTo(str2);

        System.out.println(i);
    }
}
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
Gurman8r
  • 301
  • 1
  • 4
  • 19
  • 6
    Welcome to Stack Overflow - although I think you slightly misunderstand it's purpose. SO is not here to solve your homework for you! It is expected that you have attempted the problem, and that you provide details about your attempts to the community. Good luck! – Lawrence Nov 10 '13 at 22:26
  • Well alrighty then, allow me to rephrase my inquiry... How do I compare two strings and check which has the "greater" value? – Gurman8r Nov 10 '13 at 22:35
  • 1
    @user2977234 First you gotta provide us with some sort of attempt. I'd start by comparing the first character of each String, if they are the same then look at the second. From that point on it's `substrings` `.equals()` and yeah! – Tdorno Nov 10 '13 at 22:38
  • 1
    This doesn't appear to be Javascript but Java. You've confused someone into posting a Javascript answer! – Waleed Khan Nov 10 '13 at 22:57
  • Suggest you read the docs for compareTo: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo(java.lang.String) – Evan Trimboli Nov 10 '13 at 22:59
  • @WaleedKhan where does it say that it's javascript? I'm pretty sure it says java... – Gurman8r Nov 10 '13 at 23:09
  • Sorry for mucking anything up if i did so :( – Gurman8r Nov 10 '13 at 23:19

1 Answers1

0

just save the strings in an array and use the sort function provided by java.util.Arrays :

String [] strings = {"zzz", "bbb", "aaa"};

//Sort array in ascending order
Arrays.sort(strings);

for (String str : strings) {
    System.out.println(str);
}

// aaa bbb zzz
Giuseppe Pes
  • 7,772
  • 3
  • 52
  • 90