【问题标题】:Out of bounds error in a loop循环中的越界错误
【发布时间】:2011-12-21 18:22:14
【问题描述】:
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);

}

在 int c = 动物[j].compareTo(动物[j+1]);由于某种原因,它给了我一个超出范围的错误

【问题讨论】:

  • 在这种情况下n 是什么?是a 中的对象数吗?如果是这样,在循环的第一次迭代中,j+1 将超出范围。

标签: loops indexoutofboundsexception


【解决方案1】:

好像是n &gt;= animals.length

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

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2017-05-12
    • 2019-11-16
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多