Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Y07sumPrimeNonPrime {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- boolean nonPrimeNum = false;
- int i = 2;
- int primeNum = 0;
- int nonPrime = 0;
- while (true) {
- String command = scanner.nextLine();
- if (command.equals("stop")) {
- break;
- }
- int num = Integer.parseInt(command);
- if (num < 0) {
- System.out.println("Number is negative.");
- } else {
- i = 2;
- while (i <= num / 2) {
- // condition for nonprime number
- if (num % i == 0) {
- nonPrimeNum = true;
- }
- ++i;
- }
- if (num == 1 || num == 0) {
- nonPrime += num;
- continue;
- }
- if (!nonPrimeNum) {
- primeNum += num;
- } else {
- nonPrime += num;
- nonPrimeNum = false;
- }
- }
- }
- System.out.printf("Sum of all prime numbers is: %d%n", primeNum);
- System.out.printf("Sum of all non prime numbers is: %d", nonPrime);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment