循环中的超出界限错误

时间:2011-11-04 05:47:46

标签: loops indexoutofboundsexception

public static void bubbleSort(Farm a[], int n) {
String[] animals = getString(a);

for(int i = 0; i < n - 1; i++)  {

  boolean swapped = false;
  for(int j = 0; j < n - 1 - i; j++) {

    int c = animals[j].compareTo(animals[j+1]);
    if(c > 0) {
      swap(animals, j, j+1);
      swapped = true;
    }
  }
  if(!swapped) 
    break;
}
for (int i = 0; i < a.length; i++)
  if(a[i] != null)
  System.out.println(a[i].animal);

}

in int c = animals [j] .compareTo(animals [j + 1]);由于某种原因它给了我一个出界的错误

1 个答案:

答案 0 :(得分:1)

好像是n >= animals.length

再次检查for循环中的边界值