Classify Numbers in Java

The following Java program application counts the number of odd and even numbers. The program also counts the number of zeros. I will be using the JCreator IDE in developing the program. To start in this tutorial, first open the JCreator IDE, click new and paste the following code.
  1. import java.util.*;
  2. public class ClassifyNumbers
  3. {
  4. static Scanner console = new Scanner (System.in);
  5.  
  6. static final int N = 20;
  7.  
  8. public static void main (String[] args)
  9. {
  10. //declare variables
  11.  
  12. int counter; //loop control variable
  13. int number; //variable to store the new number
  14.  
  15. int zeros = 0;
  16. int odds = 0;
  17. int evens = 0;
  18.  
  19. System.out.println("Please enter " + N
  20. + " integers, positive, negative, or zeros: ");
  21.  
  22. for (counter = 1; counter <= N; counter++)
  23. {
  24. number = console.nextInt();
  25. System.out.print(number + " ");
  26.  
  27. switch (number % 2)
  28. {
  29. case 0: evens++;
  30. if (number == 0)
  31. zeros++;
  32. break;
  33. case 1:
  34. case -1: odds++;
  35. }
  36. }
  37. System.out.println();
  38. System.out.println("There are " + evens + "evens "
  39. + "which also includes "
  40. + zeros + " zeros");
  41. System.out.println("Total number of odds is: " + odds);
  42. }
  43. }
Sample run:
  1. Please enter 20 integers, positive, negative, or zeros:
  2. 1 2 3 4 5 6 7 8 9 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 0
  3. 1 2 3 4 5 6 7 8 9 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 0
  4. There are 10evens which also includes 2 zeros
  5. Total number of odds is: 10
The program work as follows: The statement
  1. System.out.println("Please enter " + N
  2. + " integers, positive, negative, or zeros: "); prompts the user to enter integers, positive, negative or zero numbers.
  3.  
  4. The statement <java number = console.nextInt();
  5. System.out.print(number + " ");
gets the next number and outputs the number. The statement  for (counter = 1; counter <= N; counter++) process and analyze the 20 numbers. The statement
  1. System.out.println("There are " + evens + "evens "
  2. + "which also includes "
  3. + zeros + " zeros");
  4. System.out.println("Total number of odds is: " + odds);
print the result and output the values of the variables zeros, evens and odds.

Add new comment