0
Getting error that my array might not be initialized. I'm trying contain all prime numbers within a given number into an array.
import java.util.Scanner; class Program { public static int isPrime(int a) { int sum=0; for(int i=1;i<=a;i++) { if(a%i==0) { sum+=i; } } if(sum==a+1) return 1; else return 0; } public static void main(String[] args) { int arr[]; int j=0; Scanner sc =new Scanner(System.in); int x =sc.nextInt(); for(int i =2;i<x;i++) { if(isPrime(i)==1) { arr[j]=i; j++; } } for(int k=0;k<arr.length;k++) { System.out.println(arr[k]); } } }
2 Answers
+ 2
Since the array has not been initialized it does not have a size/nothing stored in memory for the variables.
You could do something like:
// At this spot:
int x = sc.nextInt();
arr = new int[x];
// this is what you need
Something along those lines.
Also your isPrime method might as well be a boolean instead of int.
0
Thanku Rrestoring faith but giving a dimension length to the array as x(which is the input number ) will far exceed the length of the array that I intend to create. Because obviously the number of prime numbers(j) will be less than the number(x) itself.