myrdok123

P03SumPrimeNonPrime

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