Plaix
Plaix

Reputation: 881

Please what am i doing wrong in this code

I wrote a sorting function it works sorts everything, but if there is a space between two words it sorts the space to the beginning and removes the last string element why is this happening? i tried String.trim() method to get rid of white spaces but it didn't work, i need help

private void SortStringsActionPerformed(java.awt.event.ActionEvent evt) {                                            
         // TODO add your handling code here:
         String str = TextArea.getText();

     String[] words = str.split(" ");

        int length = words.length;
    String temp; 
    for(int i=0; i<=length-1; i++){
            for(int j=0; j <length-1;j++){
            if(words[i].compareToIgnoreCase(words[j]) == 0 ){}
            else if (words[i].compareToIgnoreCase(words[j]) < 0){   
                                temp = words[i].trim();
                words[i] = words[j].trim();
                words[j] = temp;
            }else{} 
        }
    }
        /*
    String str2="";
    for (int i=0; i < length-1; i++) {
            str2+=words[i]+" ";
        }
        */
        StringBuilder str2 = new StringBuilder();
        for(int i=0; i<length-1; i++) {
            str2.append(words[i]).append(" ");
        }
        TextArea.setText(str2.toString());

    }                            

Upvotes: 0

Views: 127

Answers (3)

Michael
Michael

Reputation: 1237

First of all, it will be best not to use for(int i=0; i<=length-1; i++) but rather for(int i = 0; i < length; i++).

This is also the reason why your last element is removed - you've used for(int i=0; i<length-1; i++) instead of for(int i=0; i<length; i++)

EDIT: And to disable the spaces you can use: TextArea.setText(str2.toString().trim());

Upvotes: 1

arutaku
arutaku

Reputation: 6107

If you want to sort "whatever" just use java.utils.Collections class. It has sorting methods for elements that implement Comparable:

static <T extends Comparable<? super T>> void sort(List<T> list)

Or you can specify your own comparator:

static <T> void sort(List<T> list, Comparator<? super T> c)

It would be easier than writing and debugging your own sorting code.

Here is an example: http://www.vogella.com/blog/2009/08/04/collections-sort-java/

Upvotes: 1

Related Questions