如何从main中的方法打印出数组?

brqmpdu1  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(316)

我创建了一个用素数填充数组的方法。但是,我很难理解,如何才能返回后,它已填写的主要方法打印出来呢?像这样返回给我一个错误,它找不到这样一个符号。

public static int[] fillArray(int a){
        int[] arr = new int[a];
        int m = 0;
        for (int i = 1; m < arr.length; i++){
            if (isPrime(i)){
                arr[m] = i;
                m++;
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        System.out.println(arr);
    }
qhhrdooz

qhhrdooz1#

我建议,你可以做如下的事情,

public static int[] fillArray(int a){
    int[] arr = new int[a];
    int m = 0;
    for (int i = 1; m < arr.length; i++){
        if (isPrime(i)){
            arr[m] = i;
            m++;
        }
    }
    return arr;
}

public static void main(String[] args) {
    int a = Integer.parseInt("5"); //Pass a hard coded value or Read it from Scanner class and pass the same as argument
    int[] arr = fillArray(a);
    System.out.println(arr); //This line not actually prints the values of array instead it prints the Object representation of the array

   // Below small piece of code will print the values of the array
    for(int val:arr){
         System.out.println(val);
     }

}
eeq64g8w

eeq64g8w2#

public static int[] fillArray(int a){
        int[] arr = new int[a];
        int m = 0;
        for (int i = 1; m < arr.length; i++){
            if (isPrime(i)){
                arr[m] = i;
                m++;
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int[] arr = fillArray(a); // This line was missing
        System.out.println(Arrays.toString(arr));
    }

在此处了解有关调用方法的更多信息:https://docs.oracle.com/javase/tutorial/java/javaoo/methods.html

相关问题