gpt4 book ai didi

java - 排序中的 ArrayIndexOutOfBounds

转载 作者:行者123 更新时间:2023-11-30 07:17:16 25 4
gpt4 key购买 nike

我按如下方式编写了我的排序问题,但我收到了一个ArrayIndexOutOfBounds 异常。我无法弄清楚。请帮忙。

System.out.println("Enter the total no of digits to sort:-  ");

n = Integer.parseInt(br.readLine());
x = new int[n];

System.out.println("Enter the elements:- ");

for(i = 0; i < n; i++)
x[i] = Integer.parseInt(br.readLine());

for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(x[j] > x[j+1]) //ascending order
{
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}

最佳答案

由于 j 上升到 nj+1 越界。您需要将其更改为

for(j=0;j<n-1;j++)

这样做可以确保 x[j+1] 在范围内。

关于java - 排序中的 ArrayIndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318534/

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