【问题标题】:java.lang.ArrayIndexOutOfBoundsException error when I trying to make Bubble sort当我尝试进行冒泡排序时出现 java.lang.ArrayIndexOutOfBoundsException 错误
【发布时间】:2012-03-30 15:43:06
【问题描述】:

我正在尝试进行冒泡排序,这是我的代码:

import java.util.Random;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {

    double[] test = new double[5];
    double t;

    //Set random value to each of elements
    for(int i = 0;i<test.length;i++){
        test[i] = Math.round((100*Math.random()));
        System.out.println(test[i]);
    }

    //Bubble Sort
    for(int i = 0;i<test.length;i++){   

        for(int k = 0;k<test.length-1;k++){

            int x = i+1;                
            if(test[i]>test[x]){
                t = test[i];
                test[i] = test[x];
                test[x] = t;        

            }               
        }           
    }                   
  }

}

然后我启动它,它会抛出一个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:24)

【问题讨论】:

    标签: java sorting bubble-sort


    【解决方案1】:

    i 上升到数组的长度,然后您将 x 设置为超过该长度!因此,您尝试访问超出数组末尾的元素。

    您可以在排序代码中使用i &lt; test.length - 1,或者检查以确保您不会尝试将最后一个元素与其后的元素交换。

    【讨论】:

      【解决方案2】:

      我认为,在您的内部循环中,您希望使用 k 而不是 i

      【讨论】:

        【解决方案3】:

        行“i = x + 1;”是你的问题。当您的计数器 x 为 4 时,这会将 i 变为 5。当您尝试获取 test[5] 的值时,您会超出数组的范围。

        【讨论】:

          猜你喜欢
          • 2014-08-31
          • 2017-04-25
          • 1970-01-01
          • 2016-01-19
          • 2017-11-11
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多