我目前有以下代码。我在这一行得到 ArrayIndexOutofBoundsException。
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)
对应的行如下。
dta[flagcounter] = dta[x];
sortValues = s.sort(sortValues,counter, sortBy, searchterm);
我很确定它不会超过数组的长度......
有人可以帮忙吗?谢谢!
程序代码如下
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);
}