Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings . For example if I implement :

        testsort t = new testsort();
        t.i("abc");
        t.i("aab");
Can anybody see the error and help me fix this error please ?

Thank you



Here is the code :



public class testsort {

private int length;
String[] data;


   public testsort() 
   {

       length = 0;

   }

public void i(String value)
{


   data[length] = value;   
  SetSorted(data);
   length++;
}


public void SetSorted(String data[])
{


 for(int i = data.length-1; i >= 0; i--) 
 {
    for(int j = 0; j < i; j++) {
        if(data[j].compareTo(data[j + 1]) > -1) {
            String temp = data[j];
            data[j] = data[j + 1];
           data[j + 1] = temp;
        }
    }
}

for(int i = 0; i < data.length; i++) 
    {
    System.out.print(data[i] +" ");
     }



  }



}
Posted
Comments
ZurdoDev 28-Jan-15 7:43am    
Debug it and let us know what the problem is.
Pandu Rang 29-Jan-15 7:22am    
this seems to be a duplicate question

1 solution

You're not allocating data in the constructor of testsort, so it's always null. Because of this, any call trying to access data, like data[length] = value, will fail.

You need to make sure data has room for the number of elements you plan to add, or have it dynamically resize as new items are added.

Hope this helps,
Fredrik
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900