2015-06-23 167 views
1

這是我到目前爲止有:傳遞一個數組通過構造

import java.util.*; 

public class SArray { 

    private int[] array; 

    public SArray(int a[]) { 
     this.array = a; 
    } 

    public String toString() { 
     String arrayString = ""; 
     int i = 0; 
     while (i < array.length) { 
      arrayString = arrayString + array[i]; 
      i++; 
     } 
     return arrayString; 
    } 

    public static void main(String[] args) { 
     SArray tester = new SArray(new int[] { 23, 17, 5, 90, 12, 44, 38, 84, 
       77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49 }); 
     tester.toString(); 
    } 
} 

我擡頭如何通過構造函數傳遞數組,這就是我想出了但沒有值實際上進入陣列我想知道爲什麼?

回答

2

這些值將進入數組,但您無所事事。也許你想/需要顯示的值,所以使用System.out.println

public static void main(String[] args) { 
    SArray tester = new SArray(new int[] {23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49}); 
    //now you're doing something with the value of toString 
    System.out.println(tester); 
} 
+0

哇你」對了,這是一個非常愚蠢的問題對不起跑了3個小時的睡眠 –

1

數組是有...的樣子:

public static void main(String[] args) { 
     NewClass tester = new NewClass(new int[]{23, 17, 5, 90, 12, 44, 38, 84, 
      77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49}); 
     for(int i = 0; i < tester.array.length; i++){ 
      System.out.println(tester.array[i]); 
     } 
    } 

這是輸出:

23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, 49, 
相關問題