2014-07-05 125 views
0

任何人都可以帮助我摆脱这个Exception线程“主”java.lang.ArrayIndexOutOfBoundsException异常:10

“在线程异常 ”主“ java.lang.ArrayIndexOutOfBoundsException:10”

import java.util.*; 
public class AscendingOrder { 
    public static void main(String[] args) { 

     int i, j, temp; 
     int a[] = { 
      10, 5, 7, 98, 45, 34, 38, 56, 34, 93 
     }; 

     for (i = 0; i < a.length; i++) { 
      for (j = i + 1; j < a.length - 1; j++) { 
       if (a[i] > a[j]) { 
        temp = a[i]; 
        a[i] = a[j]; 
        a[j] = temp; 
        i++; 
       } 
      } 
     } 
     System.out.println(a[i]); 
    } 
} 

回答

1

在异常最后陈述书

的System.out.println(A [1 ]);

这不是打印你的整个数组,而是你的数组的第11个索引不在那里。 所以你会得到例外。 因为当for循环之后结束I值由1

递增与尝试

的System.out.println(Arrays.toString的(a));

0

更改代码

public static void main(String[] args) { 

    int a[] = {10, 5, 7, 98, 45, 34, 38, 56, 34, 93}; 
    for (int i = 0; i < a.length -1; i++) { 
     for (int j = i + 1; j < a.length; j++) { 
      if (a[i] > a[j]) { 
       int temp = a[i]; 
       a[i] = a[j]; 
       a[j] = temp; 
      } 
     } 
    } 
    for (int k = 0; k < a.length; k++) { 
     System.out.println(a[k]); 

    } 
} 

您可以防止这些例外声明变量里面的for循环。

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

1

因为在System.out.println(a[i]);i等于a.length(每for循环条件),还你有你的循环条件交换

for (i = 0; i < a.length - 1; i++) { 
    for (j = i + 1; j < a.length; j++) { 
    if (a[i] > a[j]) { 
     temp = a[i]; 
     a[i] = a[j]; 
     a[j] = temp; 
    } 
    } 
} 
System.out.println(Arrays.toString(a)); // <-- print the entire array 
0

这是最后陈述。 改变它在

System.out.println(a[i-1]); 
0

你可能想看看java.util.Arrays类。书中有一个很好的方法,你可能会发现有用:排序(INT [])

- 托马斯

0
import java.util.*; 

公共类AscendingOrder { 公共静态无效的主要(字串[] args){

int i,j,temp ;  
int a[]={10,5,7,98,45,34,38,56, 34,93}; 

for (i=0; i<a.length;i++){   
    for (j=i+1; j<a.length-1;j++){    
     if(a[i] > a[j]){     
      temp=a[i]; 
      a[i]=a[j]; 
      a[j]=temp;     
      i++; 
     } 
    } 
    System.out.println(a[i]); 
}       

}

0

正如塔伦说,问题是你最后一次 '的println' 语句。

当你的i = 9迭代结束时,'i ++'项让你的变量增加并且值为10.当然,你永远不会进入循环,但是你仍然试图打印i [10]。这超出了从i [0]延伸到i [9]的数组的界限。

0

使用Arrays utility打印您array a对象。

计划:

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

      int i, j, temp; 
      int a[] = { 
       10, 5, 7, 98, 45, 34, 38, 56, 34, 93 
      }; 

      for (i = 0; i < a.length; i++) { 
       for (j = i + 1; j < a.length - 1; j++) { 
        if (a[i] > a[j]) { 
         temp = a[i]; 
         a[i] = a[j]; 
         a[j] = temp; 
         i++; 
        } 
       } 
      } 
      System.out.println(Arrays.toString(a)); 
     } 
} 

输出:

[5, 7, 10, 45, 34, 38, 56, 34, 98, 93] 
相关问题