I created a method that fills an array with prime numbers. However, I am struggling to understand how can I return it after it has been filled to the main method to print it? Returning like this gives me an error that it cannot find such a symbol.
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);
}
I would suggest, you can do something like below,
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));
}
Learn more about calling methods here: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.