Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This is the basis for the third task in Lab 12,
- * Applications. The task is to count the different
- * kinds of numbers. The numbers between zero and
- * nine, inclusive, are divided into the following
- * categories:
- * <li>Identity - the additive identity element, zero;
- * and the multiplicative identity element, one.
- * <li>Prime - a number that can only be evenly divided
- * by itself and one.
- * <li>Composite - a number that is the product of primes,
- * two or more, not necessarily different prime numbers.
- * </ul>
- * The numbers outside of the range 0-9 will simply
- * be counted as other.test.
- * <p>
- * You might recognize this as an adaptation of the example
- * showing how to write a switch statement. This now has
- * been updated to include user input, using Scanner.
- */
- public class CountNumbers {
- /**
- * The application method
- */
- public static void main(String[] args) {
- CountNumbers numbers = new CountNumbers();
- System.out.println("Please enter an integer:");
- // Checking for an integer
- if (numbers.in.hasNextInt()) {
- // Read the input
- int input = numbers.in.nextInt();
- numbers.switchCounter(input);
- }
- else {
- // Clear scanner if it was not an integer and give an error
- numbers.in.next();
- System.err.println("Non-integer input ignored.");
- }
- numbers.printSummary();
- }
- // The fields to keep track of the counts
- private int identity;
- private int prime;
- private int composite;
- private int other;
- // The scanner
- private java.util.Scanner in;
- /**
- * The constructor initializes the fields.
- */
- public CountNumbers() {
- identity = 0;
- prime = 0;
- composite = 0;
- other = 0;
- in = new java.util.Scanner(System.in);
- }
- /**
- * This is the switch version of the counting routine.
- * @param input The value read from the user input
- */
- public void switchCounter(int input) {
- // the switch statement, based on the int value input
- switch(input) {
- // count the identity elements: 0 and 1
- case 1:
- case 0:
- identity ++;
- break;
- // count the prime numbers
- case 2:
- case 3:
- case 5:
- case 7:
- prime ++;
- break;
- // count the composite numbers
- case 4:
- case 6:
- case 8:
- case 9:
- composite ++;
- break;
- }
- }
- /**
- * Print out the summary statistics, the counts.
- */
- public void printSummary() {
- System.out.println();
- System.out.println("Here are the counts:");
- System.out.println(" " + identity + " identity elements");
- System.out.println(" " + prime + " prime numbers");
- System.out.println(" " + composite + " composite numbers");
- System.out.println(" " + other + " values out of range");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement