[英]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.