//********************************************************
// Program: Classify Numbers
// This program counts the number of odd and even numbers.
// The program also counts the number of zeros.
// Filename: ClassifyNumbers.java
//********************************************************
import java.util.*;
public class ClassifyNumbers
{
static Scanner console = new Scanner(System.in);
static final int N = 20;
public static void main (String[] args)
{
//Declare the variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
System.out.println("Please enter " + N + " integers, positive, "
+ "negative, or zeros."); //Step 2
for (counter = 1; counter <= N; counter++) //Step 3
{
number = console.nextInt(); //Step 3a
System.out.print(number + " "); //Step 3b
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1:
odds++;
}//end switch
}//end for loop
System.out.println();
//Step 4
System.out.println("There are " + evens + " evens, "
+ "which also includes "
+ zeros + " zeros");
System.out.println("Total number of odds is: " + odds);
}
}
/*
Sample Output: (In this sample run, the user input is shaded.)
********************************************************
Please enter 20 integers, positive, negative, or zeros.
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
0 0 -2 -3 -5 6 7 8 0 3 0 -23 -8 0 2 9 0 12 67 54
There are 13 evens, which also includes 6 zeros
Total number of odds is: 7
********************************************************
We recommend that you do a walk-through of this program using the above sample
input.
Note that the switch statement in Step 3c can also be written as an if...else
statement as follows:
if (number % 2 == 0)
{
evens++;
if (number == 0)
zeros++;
}
else
odds++;
No comments:
Post a Comment