Target - find all primeNumbers and create array with it What was done - created method primeReturner - return true if number prime -
private static boolean primeReturner (int i){
for (int j=2;j<i; j++){
if (i%j==0)
return false;
}
return true;
}
created method for creating numbers with prime numbers
private static void simpleArray() {
int []a = new int [100];
a[0]=1;
a[1]=2;
for (int i=2; i<a.length; i++){
if (primeReturner(i)==true){
a[i]=i;
i++;
}
}
}
Problem - i get some errors during creating array - some of item from array 0 and some its ok... and some times it return errors...
Questing - what wrong with my method simpleArray?
A little bit modify code - now it recognize all prime numbers and create array with it, but after adding 100th item in to array i get errors
code
private static void simpleArray() {
int []a = new int [100];
a[0]=1;
a[1]=2;
int count=2;
while (count<100)
for (int i=3; ; ++i){
if (primeReturner(i)==true){
a[count]=i;
count++;
}
}
for (int j=0; j<a.length; j++){
System.out.print(" " + a[j]);
}
}
private static boolean primeReturner (int i){
for (int j=2;j<i; j++){
if (i%j==0)
return false;
}
return true;
}
and main function public class Exercise_1 { private static int select;
public static void main (String[]args) throws IOException{
System.out.println("Menu:");
....
System.out.println("Array with simple numbers - enter 7");
select = getNumber ();
switch (select){
.....
case 7:{
simpleArray();
}
}
}
As result all array with prime number succsesfull created but during printing this array i get java.lang.ArrayIndexOutOfBoundsException errors...
How to resolve this error?
main
method? In code you provided, in all places where array is accessed, it is guaranteed that index is below array length. – Mikhail VladimirovprimeReturner (int i)
you can improve the loop:int upperbound=Math.sqrt(i); for (int j=2;j<=upperbound; j++)
. And if you want to have all prime number up to a given value, you should consider implementing the Sieve of Eratosthenes. – MrSmith42