繁体   English   中英

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

[英]How can I print out array from a method in main?

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

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

我建议,您可以执行以下操作,

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

}
     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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM