2015-05-29 79 views
-1

如何可以通過foreach循環方法打印一維數組的元素一維陣列打印

public class SingleArrayPrac { 

    public static void main(String[] args) { 
     int[] array = { 1, 2, 3, 4 }; 

     // for(int row : array) This way i can print array but i want to print through method, How? 
     // System.out.println(row); 
     for (int print : array) { 
      printRow(print); 
     } 
    } 

    public static void printRow(int row) { 
     for (int print : row) { // Error at Row 
      System.out.println(print); 
     } 
    } 
} 
+0

在printRow方法中row是一個整數,你會如何遍歷一個整數?你只需要打印參數。 – lateralus

+0

您的'printRow'方法中的'row'變量已包含數組元素。所以你只需要用'println'在'printRow'中打印'row', –

回答

0

閱讀下面的代碼中的註釋爲解釋:

public class SingleArrayPrac { 

    public static void main(String[] args) { 
     int[] array = { 1, 2, 3, 4 }; 

    /* 
    Here print variable will hold the next array element in next iteration. 
    i.e in first iteration, print = 1, in second iteration print = 2 and so on 
    */ 
     for (int print : array) { 
      //You pass that element to printRow 
      printRow(print); 
     } 
    } 

    public static void printRow(int row) { 
     //This will print the array element received. 
     System.out.println(print); 
    } 
} 

另解決方案可以是:

public class SingleArrayPrac { 

    public static void main(String[] args) { 
     int[] array = { 1, 2, 3, 4 }; 

     printRow(array); //Here you pass the whole array to printRow 
    } 

    public static void printRow(int[] row) { 
     /* 
      The array is received in row variable and than each element of the array is printed. 
     */ 
     for (int print : row) { 
      System.out.println(print); 
     } 
    } 
} 
1

你的問題在於你聲明你的printRow方法。你傳遞一個int,你應該傳遞一個int []數組。這會導致錯誤,因爲您正在嘗試通過不是數據集合的變量。它應該是這樣的:

public static void printRow(int[] row) { 

    for (int print : row) { 
     System.out.println(print); 
    } 
} 

現在,當你想打印你的數組只需調用printRow(array)其中array是一個int []。