Frage

I am currently trying to sort an array alphabetically I am having troubles with step 3. Here is my current code :

import java.util.Arrays;
import hsa.Console;

public class HowToSortAnArray {
    static Console c;
    public static void main(String[] args) {
        c = new Console ();

        String[] myStrArray = new String[500];

        for(int i=0;i<5;i++) {
            c.print("Input word: ");
            myStrArray[i]=c.readLine();
        }

        Arrays.sort(myStrArray, String.CASE_INSENSITIVE_ORDER);

        for (int a = 0; a < myStrArray.length; a++) {
           c.println(myStrArray[a]);
        }
    }
}

Can anyone explain to me why this code isn't working an this one is:

String[] words = new String[] {"b", "b", "a", "D"};
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);

for (int a = 0; a < words.length; a++) {
    c.println(words[a]);
}

Does it have something to do with declaring array values? I am pretty lost.

War es hilfreich?

Lösung

you need to change your line to:

 for(int i=0;i<myStrArray.length;i++);





import java.io.Console;
import java.util.Arrays;

public class HowToSortAnArray {
static Console c;
public static void main(String[] args) {

    String[] myStrArray = new String[5];

    for(int i=0;i<myStrArray.length;i++) {
         System.out.println("Input word: ");
        myStrArray[i]= "abdfg";
    }

    Arrays.sort(myStrArray, String.CASE_INSENSITIVE_ORDER);

    for (int a = 0; a < myStrArray.length; a++) {
         System.out.println(myStrArray[a]);
    }
}

}

Andere Tipps

This code does the job:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class TestSort {
    public static void main(String[] args) {
        Set<String> wordsSet = new HashSet<>();
        Scanner s = new Scanner(System.in);
        while (true) {
            System.out.print("Input word: ");
            String newLine = s.nextLine();
            if (!wordsSet.add(newLine)) {
                break;
            }
        }
        String[] words = wordsSet.toArray(new String[wordsSet.size()]);
        Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
        System.out.println(Arrays.toString(words));
        return;
    }
}

You can use java.util.Set to make sure that there are no duplicates. java.util.Set.add returns false if what you are adding is already present in the set, so you can use this as a condition to exit the input-enter loop.

Replacing your hsa.Console with a java.io.Console will fix your errors. I.e.

import java.io.Console;

...

c = System.console();

...

Then use c.printf(...) instead of c.println().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top