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] +" ");
}
}
}
IndexOutOfBoundsExceptionbut can you please post the stack-trace of your error.String[]data array, have you?ArrayListas an alternative to standard arrays. WithArrayListyou don't have to worry about making sure your array is large enough to hold the data to insert. ChangeString[] datatoList<String> data. Add into your constructorthis.data = new ArrayList<String>()and then look at how to use theListinterface.