I currently have the following code. I get ArrayIndexOutofBoundsException at this line.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Module3_1_Sort.sort(Module3_1_Sort.java:70)
at Module3_1.s_2d_string(Module3_1.java:155)
The corresponding lines are as follows.
dta[flagcounter] = dta[x];
sortValues = s.sort(sortValues,counter, sortBy, searchterm);
I am pretty sure that it does not exceed the length of the Array…
Can anybody help? Thanks!
code of program follows
static public void s_2d_string () {
c.println("2D String Array Program");
int counter,x;
c.print("How many entries do you wish to sort? ");
counter = c.readInt();
String[][] sortValues = new String[counter+1][2];
for (x=0;x<counter;x++) {
c.print("Enter book name: ");
sortValues[x][0] = c.readLine();
c.print("Enter book author: ");
sortValues[x][1] = c.readLine();
}
c.print("Which column would you like to sort by? 1 or 2? ");
int sortBy = c.readInt();
sortBy = sortBy-1;
c.print("Enter search term: ");
String searchterm = c.readLine();
sortValues = s.sort(sortValues,counter, sortBy, searchterm);
int flagcounter_int = Integer.parseInt(sortValues[0][0]);
c.println(flagcounter_int + " results found.");
for (x=0;x<flagcounter_int;x++) {
c.println(sortValues[x+1][0] + ", " + sortValues[x+1][1]);
}
}
static public String[][] sort (String dta[][], int totalNo, int sortBy, String searchterm) {
boolean found = false;
int flagcounter = 0;
for (int x=0; x<dta.length;x++) {
if (sortBy == 0) {
if (searchterm.equalsIgnoreCase(dta[x][0])) {
found = true;
flagcounter = flagcounter+1;
dta[flagcounter] = dta[x];
}
}
if (sortBy == 1) {
if (searchterm.equalsIgnoreCase(dta[x][1])) {
found = true;
flagcounter = flagcounter+1;
dta[flagcounter] = dta[x];
}
}
}
String flagcounter_string = Integer.toString(flagcounter);
dta[0][0] = flagcounter_string;
return (dta);
}
Look at the
forloop and the way you handleflagcounterinside it. Theforloop says:and the
flagcounteris incremented when you find the search term, before it’s used as an index:What happens is that if you have a match in the first row, you keep finding it in the next row (because you overwrite it) and you end up going out of bounds.
Let’s look at an example. Say you have this as an input:
So
dtawill be like this:Say you’re looking for author “Jim Butcher”. So when you enter the loop, you have
x = 0, flagcounter = 0. You immediately find the match and what happens is:So now the
dtaarray looks like this:You can see what happens: you keep assigning the previous row to the next row and at last you’re in the situation where
x = 2andflagcounter = 2and you try to dodta[3] = dta[2], which goes out of bounds ofdta.As Sabbath suggested, you need to correct the
forloop. However, I think you’re probably missing something more to make it do what you want. Among other things, there’s the fact thatdta[flagcounter] = dta[x];does not assign values in thexrow to theflagcounterrow, but actually makes theflagcounterrow point toxrow by reference.