user2407152
user2407152

Reputation: 49

Sorting class arrays?

I have a program which sorts words in alphabetical order, these words come from the user who inputs them (I'm using a GUI). Unfortunately the "sort" part of the code has some lines underlined for reasons I'm not aware of yet, but I have a suspicion it has to do with the class/array. Any tips on how to correct this would be fantastic!

Under "Public" I've created a class and array.

class Word{
    String word;
    Word(String _word) {
        word= _word;
    }
}

ArrayList <Word> small = new ArrayList <Word>(); //array for words...

Under the "Sort button" actionPerformed which is on GUI...

String word;
Word b = new Word(word); //these two lines stores words inputted by user
small.add(b); //second line

//begins to sort
for (int k = 0; k < word.length(); k++) {
    word[k] = word; //underlined red "array required"
    int x;
    for (int i = 0; i < word.length(); i++) {
        // Assume first letter is x
        x = i;
        for (int j = i + 1; j < word.length(); j++) {
            if (word[j].compareToIgnoreCase(word[x]) < 0) { 
            //underlined red "array required"
                x = j;
            }
        }
        if (x != i) {
            //swap the words if not in correct order
            final String temp = word[i]; //underlined red "array required"
            word[i] = word[x]; //underlined red "array required"
            word[x] = temp; //underlined red "array required"
        }
        istArea.append(word[i] + "\n");// Output ascending order
        //underlined red "array required"
    }
}

Upvotes: 0

Views: 123

Answers (2)

BlackHatSamurai
BlackHatSamurai

Reputation: 23493

If you want this to work, you need to declare an array of Strings:

String[] myArray;

Then you can say:

myArray[k] = word;

And so on...

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67370

This does not compile. You can't type word[x] because word is not an array, it's a String. If you're trying to get the first character of the String, use this instead:

char c = "foo".charAt(0);

You can change that 0 to be x in your algorithm.

Alternatively, you could do this:

char[] chars = "foo".toCharArray();

And now every where you're using words[x] you can now use chars[x] and it should compile.

But, this is one of just many of your errors:

  1. You have l on its own line without a semicolon. I don't even know your intent here, but you can't do that. Here are some other issues:
  2. small is not defined. What is this?
  3. istArea is not defined. What is this?
  4. What is word[k] = word; supposed to mean?

Upvotes: 3

Related Questions