gpt4 book ai didi

java - 如何在冒泡排序中修复java中的 'java.lang.ArrayOutOfBound exception'

转载 作者:行者123 更新时间:2023-12-02 03:04:51 26 4
gpt4 key购买 nike

当我尝试运行冒泡排序代码时,出现异常java.lang.ArrayOutOfBound。您能帮我解决这个异常吗?

public class bubblesort {
public static void main(String args[]) {
int[] a = {30, 20, 7, -9, 0, 3, 122};
int temp = 0;
for (int b = a.length - 1; b > 0; b--) {
for (int i = 0; i <= a.length - 1; i++) {
if (a[i] > a[i + 1])
swap(a, i, i + 1);

}
}
for (int c = 0; c <= a.length - 1; c++) {
System.out.println(a[c]);
}
}

public static void swap(int[] arr, int i, int j) {
int temp;
if (i == j) {
return;
}
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

最佳答案

for(int i=0;i<=a.length-1;i++){
if(a[i]>a[i+1])

当你使用a[i+1]时,你超出了数组的范围。在您的代码中,您的索引会上升到最后一个单元格。改变你的for循环:

 for(int i=0;i<a.length-1;i++){

关于java - 如何在冒泡排序中修复java中的 'java.lang.ArrayOutOfBound exception',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com