Java Alphabetizing Strings

后端 未结 7 1247
悲哀的现实
悲哀的现实 2021-01-19 04:27

I have a project for class were I need to get 4 different strings inputted and then output them in alphabetical order.

So far I have this:

String wd1         


        
7条回答
  •  礼貌的吻别
    2021-01-19 04:56

    For comparing more than 2 strings you should put the strings in an array and then run them through a sorting method

    public class SortLetters2 {
    public String[] sort(String[] asd) {
        String[] sorted = asd.clone();
        for (int i = 0; i < sorted.length; i++) {
            for (int j = i + 1; j < sorted.length; j++) {
                int compare = sorted[i].compareTo(sorted[j]);
                if ((compare > 0) && (i != j)) {
                    //compare two strings
                    String temp = sorted[j];
                    sorted[j] = sorted[i];
                    sorted[i] = temp;
                }
            }
        }
        return sorted;
    }
    public static void main(String[] args) {
        SortLetters2 list1 = new SortLetters2();
        //SortLetters2 is the class name
        Scanner scan1 = new Scanner(System.in);
        String wd1, wd2, wd3, wd4;
        System.out.println("Type Word One: ");
        wd1 = scan1.next();
        System.out.println("Type Word Two: ");
        wd2 = scan1.next();
        System.out.println("Type Word Three: ");
        wd3 = scan1.next();
        System.out.println("Type Word Four: ");
        wd4 = scan1.next();
        String array[] = {wd1, wd2, wd3, wd4};
        //set array equal to the inputs
        String[] sortedArray = list1.sort(array);
        for (int i = 0; i < sortedArray.length; i++) {
            if (i == sortedArray.length - 1) {
                System.out.println(sortedArray[i]);
            } else {
                System.out.print(sortedArray[i] + ",");
            }
        }
        //run sorting program
    }
    }
    

提交回复
热议问题