So...are you trying to add another function of adding all the prime numbers entered into the array? If so...
Seeing that you already have a prime boolean to detect if a number is prime or not, you could put another statement in the if (isPrime) loop to add the prime number passed in to a integer variable called prime_sum or whatever to hold the current prime number sum. To add a new prime into prime_sum you would do something like this:
prime_sum = prime_sum + array[i];
...meaning you'd add the current prime_sum and the array number detected to be prime into a new prime_sum. You could add this function to your main method code or make another method and call that in main, your choice.
how do i add prime numbers in this java code:
public class PrimeNumbers {
public static void main(String[] args) {
int[] array = new int[10];
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < 10; i++) {
array[i] = in.nextInt();
}
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(i);
}
}
}
}
2 answers
thanks @.