Here is the code
import java.util.Scanner;
public class oneDimensionArray {
public static void main (String[] args) {
finding(2,100);
}
public static void finding(int start, int end) {
int[] primeNumbers = new int[end];
for (int n = start; n < end; n++) {
boolean check = true;
int tryNum = 2;
while (tryNum <= n / 2) {
if (n % tryNum == 0) {
check = false;
break;
}
tryNum += 1;
}
if (check) {
primeNumbers[n] = n;
}
}
for (int i : primeNumbers) {
System.out.print(i + ", ");
}
}
}
The result successfully shows all prime numbers, but there are a lot of zeros substituting the non-prime numbers, just like this:
0, 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17, 0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0, 0, 0, 37, 0, 0, 0, 41, 0, 43
I wonder where is the problem with my code, and how everything is caused.
>Solution :
You should add a variable to store the number of primes found and do this.
public static void finding(int start, int end) {
int[] primeNumbers = new int[end];
int count = 0;
for (int n = start; n < end; n++) {
boolean check = true;
int tryNum = 2;
while (tryNum <= n / 2) {
if (n % tryNum == 0) {
check = false;
break;
}
tryNum += 1;
}
if (check) {
primeNumbers[count++] = n;
}
}
for (int i = 0; i < count; ++i) {
System.out.print(primeNumbers[i] + ", ");
}
}
output:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,