Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 通过foreach循环打印一维数组_Arrays_Static Methods - Fatal编程技术网

Arrays 通过foreach循环打印一维数组

Arrays 通过foreach循环打印一维数组,arrays,static-methods,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?

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

请阅读以下代码中的注释进行解释:

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);
        }
    }
}

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

public static void printRow(int[] row) {

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

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

在printRow方法中,row是整数,您希望如何迭代整数?您只需要打印参数。
printRow
方法中的
row
变量已经包含数组元素。因此,您只需使用
println
printRow
中打印
row