Advertisement
SophiYo

Ex07SumOfPrimeAndNonPrimeNumbers

Dec 18th, 2018
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. package O7_NestedLoops.Exercise;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Ex07SumOfPrimeAndNonPrimeNumbers {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String command = scanner.nextLine();
  10.         int sumPrime = 0;
  11.         int sumNonPrime = 0;
  12.  
  13.         while (!command.equalsIgnoreCase("stop")) {
  14.             int n = Integer.parseInt(command);
  15.  
  16.             if (n < 0) {
  17.                 System.out.println("Number is negative.");
  18.                 n=0;
  19.  
  20.             }
  21.  
  22.             boolean isPrime = true;
  23.             for (int x = 2; x <= n/2; x++) {
  24.                 if (n % x == 0) {
  25.                         isPrime = false;
  26.                         break;
  27.                     }
  28.             }
  29.             if (n==1) {
  30.                 isPrime=false;
  31.             }
  32.  
  33.             if (isPrime) {
  34.                     sumPrime += n;
  35.             } else {
  36.                     sumNonPrime += n;
  37.             }
  38.  
  39.  
  40.             command = scanner.nextLine();
  41.         }
  42.  
  43.         System.out.printf("Sum of all prime numbers is: %d%n", sumPrime);
  44.         System.out.printf("Sum of all non prime numbers is: %d%n", sumNonPrime);
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement