Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中BoundsException的ArrayOutOfBoundsException_Java_Arrays_Sorting_Indexoutofboundsexception - Fatal编程技术网

java中BoundsException的ArrayOutOfBoundsException

java中BoundsException的ArrayOutOfBoundsException,java,arrays,sorting,indexoutofboundsexception,Java,Arrays,Sorting,Indexoutofboundsexception,我有以下Java代码 public class TestArray { public static void main(String s[]) { int arr[]={23,12,1,4,1,4,23,6}; int temp=arr[0]; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr.length;j++)

我有以下Java代码

public class TestArray
{
    public static void main(String s[])
    {

        int arr[]={23,12,1,4,1,4,23,6};
        int temp=arr[0];

        for(int i=0;i<arr.length;i++)
        {
            for(int j=0;j<arr.length;j++)
            {
                if(arr[i]>arr[j+1])
                {
                    temp=arr[j+1];
                    arr[j+1]=arr[i];
                    arr[i]=temp;   
                }
                if(arr[i]==arr[j+1])
                {
                    arr[j+1]=arr[j+2];
                }
            }
       }

       for(int i=0;i<arr.length;i++)
       {
           System.out.println(arr[i]);
       }
    }
}
公共类测试阵列
{
公共静态void main(字符串s[]
{
int arr[]={23,12,1,4,1,4,23,6};
int temp=arr[0];

对于(int i=0;i当
j
arr.length-1时,尝试索引
arr[j+1]
arr[j+2]
将失败

您是否应该将索引运行到比当前少一个的位置?而且,索引
j+2
的最后一个位置看起来没有必要


作为一个样式点,请尽可能保持
temp
的范围。只有在交换两个数组元素时才需要它。

看起来您正在尝试按降序排列数组。您可以尝试以下操作:

public class TestArray
{
    public static void main(String s[])
    {

        int arr[]={23,12,1,4,1,4,23,6};
        int n = arr.length;  
        int temp = 0;  
        for(int i=0; i < n; i++){  
             for(int j=1; j < (n-i); j++){  
                 if(arr[j-1] < arr[j]){  
                     //swap elements  
                     temp = arr[j-1];  
                     arr[j-1] = arr[j];  
                     arr[j] = temp;  
                 }        
             }  
        }  
        for(int i=0;i<arr.length;i++)
        {
           System.out.println(arr[i]);
        }
    }
}
公共类测试阵列
{
公共静态void main(字符串s[]
{
int arr[]={23,12,1,4,1,4,23,6};
int n=阵列长度;
内部温度=0;
对于(int i=0;i将代码修改为

for(int i=0;i<arr.length-1;i++) {
    for(int j=i;j<arr.length-1;j++) {
        if(arr[i]>arr[j+1]) {
            temp=arr[j+1];
            arr[j+1]=arr[i];
            arr[i]=temp;   
        }
        if(arr[i]==arr[j+1]) {
            arr[j+1]=arr[j+2];
        }
    }
}

for(int i=0;iissue将出现在这里
j+2
例程的目的是什么?您想实现什么?您想实现数组排序吗?