galinyotsev123

ProgBasics07Nested-Loops-Y07sumPrimeNonPrime

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