2013-05-04 34 views
0

這裏是我的主要方法:爲什麼我在Java中看不到返回數組中的整數值?

public static void main(String[] args) { 

    int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 

    for (int i = 0; i < myArray.length; i++) { 
     System.out.println(myArray[i]); 
    } 

    int[] sortedArray = InsertionSort.sorter(myArray); 

    for (int i = 0; i < sortedArray.length; i++) { 
     System.out.println(sortedArray); 
    } 
} 

這裏是InsertionSort.sorter樣子:

public static int[] sorter(int[] a) { 

    return a; 

} 

這是輸出:

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 

那麼究竟是什麼我失蹤了?

回答

8
for (int i = 0; i < sortedArray.length; i++) { 
    System.out.println(sortedArray); 
} 

現在缺少的是數組索引:

for (int i = 0; i < sortedArray.length; i++) { 
    System.out.println(sortedArray[i]); // note the [i] 
} 

或(使用for-each循環):

for (int i: sortedArray){ 
    System.out.println(i); 
} 

什麼你做的是打印整個數組(在Java中並不漂亮)。

+1

哦,對不起,我再次感到啞巴.. – 2013-05-04 13:40:22

2
System.out.println(sortedArray); 

應該

System.out.println(sortedArray[i]); 
3

您可以使用Arrays.toString(int[])

Arrays.toString(sortedArray) 
1

正在打印的地址,而不是該數組的值。這就是爲什麼:)

相關問題