0

I need to sort the String array into least to greatest order by wordlength. I then need to print out the words next to their value.

Example Output:

1: I, U, K

6: Joseph, Delete

But I need help sorting the array first.

Code:

package Objects;

import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.lang.Object;

public class WordLength {

public static void main(String[] args) throws Exception{

    Scanner scan = new Scanner(new File("wordlength.dat"));
    int thresh = scan.nextInt();   //Scans the first integer
    String[] array = new String[thresh];   //Creates an empty array with length of the threshold 

    for(int i = 0; i < array.length; i++) {
        array[i] = scan.nextLine();

        /* I need to sort the array from least to
        greatest here so I can use the if statement
        below.
        */

        //Prints the word array from least to greatest by length
        if(array[i].length() == i) {
            System.out.print(i + ": " + array[i]);
        }
    }
}

}

1
  • 4
    Use Java Comparator for this. Commented Feb 27, 2018 at 18:27

3 Answers 3

0

You can use a custom comparator to sort the String array. For example

        String [] arrr = {"World","Ho","ABCD"};
        Arrays.sort(arrr,new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        System.out.println(arrr[0]); \\ Output Ho
Sign up to request clarification or add additional context in comments.

Comments

0

One of Arrays.sort overloads accepts Comparator as the second parameter, in which you can implement your own custom comparison function to determine whether a string should be placed before or after another simply by implementing the compare method.

Comments

-1

I don't code in Java, but would this pseudocode work?

Grab the list of words.
Loop through them.
   Get the length of the current word.
   Add that word to that array number:  a 5-letter word would go in array element 5.
Continue the loop until all the words have been added to the proper array.
Display each of the array elements.

1 Comment

Downvoter, this works in other languages. What's the problem with Java?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.