通过foreach循环打印单维数组

时间:2015-05-29 12:32:41

标签: arrays static-methods

如何通过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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您的问题出在您声明printRow方法的地方。你传递一个int应该传递一个int []数组。这会导致错误,因为您正在尝试不是数据集合的变量。它应该是这样的:

public static void printRow(int[] row) {

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

现在,当你想要打印你的数组时,只需调用printRow(array),其中array是一个int []。

答案 1 :(得分: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);
        }
    }
}