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

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.
thanks @.
Similar Questions
  1. public class PrimeNumbers {public static void main(String[] args) { int x = 100; for(int i=2; i <= x; i++) { if(i%2==0)
    1. answers icon 1 answer
  2. I am trying to run the following program and am getting this error:java.util.InputMismatchException import java.io.*; import
    1. answers icon 0 answers
    1. answers icon 0 answers
  3. without running on java, what is the final answer, please show your work.public class sample { public static void main(String[]
    1. answers icon 2 answers
more similar questions