gpt4 book ai didi

java - 按最接近零的数字对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 18:57:19 25 4
gpt4 key购买 nike

如果您想知道,我并不是尝试简单地先对数字最小的数组进行排序,而是尝试通过首先显示数字最接近 0 的数组列表来对数组进行排序。

它适用于数组中的某些元素,但当它需要向后遍历数组时,它不会......它只是抛出越界异常

这是我的代码:

package SSTF;

public class test2 {

public static void main (String[] args)
{
int[] temp_array = {9, 22, 3, -4, 5, 8};



for(int i =0; i<temp_array.length; i++)
{

System.out.print(temp_array[i] + " ");
}

System.out.println("\n\nNumbers closest to 0:\n");

closestToZero(temp_array);



}

public static void closestToZero(int[] array)
{
int num = array[0];
int absNum = Math.abs(num);


for(int i = 1; i < array.length; ++i)
{
int newAbs = Math.abs(array[i]);

if(newAbs < absNum)
{

absNum = newAbs;
num = array[i];

for(int j=0; j<array.length; j++)
{
System.out.print(array[i+j] + " ");
}
}
}
}
}

我真的希望这只是一个小问题,有人可以提供帮助,因为我不知道如何解决它:S

输出:

9    22    3    -4    5    8    

Numbers closest to 0:

3 -4 5 8 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SSTF.test2.closestToZero(test2.java:42)
at SSTF.test2.main(test2.java:18)

最佳答案

问题很可能出在这行代码上:

System.out.print(array[i+j] + "   ");

你能保证i + j始终是数组的有效索引吗?请记住,有效索引必须介于 0 和 size - 1 之间,其中 size 是数组元素的数量。

关于java - 按最接近零的数字对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503021/

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