java冒泡排序if语句超出范围

时间:2019-12-18 09:38:16

标签: java arrays sorting if-statement

我在运行冒泡排序时遇到了麻烦,它没有显示语法错误,并且每当我运行时,它都会在第13行(即if语句)上显示java.lang.ArrayIndexOutOfBoundsException

import java.util.*;

公共类Array3 {

public static void main(String[] args) {


    int[] numbers = {1, 5, 2, 6, 3, 8, 9, 4, 7};
    int temp = 0;       


    for(int i = 0 ; i <= numbers.length - 1 ; i++) {                        
        for (int j = 0 ; j <= numbers.length - 1 - i; j++) {
            if(numbers[j] > numbers[j + 1]) { //error is in this line
                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
            }
        }
    }
    for(int i = 0 ; i <= numbers.length ; i++) {
        System.out.print(numbers + ", ");
    }
}

}

2 个答案:

答案 0 :(得分:0)

在第一和第二个for循环中删除等于运算符,或从长度中删除-1。

public class Array3 {

public static void main(String[] args) {


    int[] numbers = {1, 5, 2, 6, 3, 8, 9, 4, 7};
    int temp = 0;       

    //Remove the equal operator in first for loop   
    for(int i = 0 ; i < numbers.length - 1 ; i++) {  
     //Remove the equal operator in second for loop                      
        for (int j = 0 ; j < numbers.length - 1 - i; j++) {
            if(numbers[j] > numbers[j + 1]) { //error is in this line
                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
            }
        }
    }
   // you should use number[i],and remove '=' operator or use -1 here.
    for(int i = 0 ; i < numbers.length ; i++) {
        System.out.print(numbers[i] + ", ");
    }
}
}

答案 1 :(得分:0)

此行表示您遍历表。 j值可以是表格的最后一个索引,因为numbers.length - 1指向最后一行(记住表格索引从0开始)。

for (int j = 0 ; j <= numbers.length - 1 - i; j++)

执行numbers[j + 1]时,如果j值位于表的最后一个索引上,则j + 1将引用表的 out 行抛出java.lang.ArrayIndexOutOfBoundsException

将循环条件从j <= numbers.length -1 -i更改为j < numbers.length -1 -i将解决您的问题。