Java Reference
In-Depth Information
Now let us write a program to find out the Chinese Zodiac sign for a given year. The
Chinese Zodiac is based on a twelve-year cycle, with each year represented by an animal—
monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, or sheep—in this cycle,
as shown in Figure 3.7.
rat
pig
0: monkey
1: rooster
2: dog
3: pig
4: rat
5: ox
6: tiger
7: rabbit
8: dragon
9: snake
10: horse
11: sheep
ox
dog
tiger
rooster
year % 12 =
rabbit
monkey
dragon
sheep
snake
horse
F IGURE 3.7
The Chinese Zodiac is based on a twelve-year cycle.
Note that year % 12 determines the Zodiac sign. 1900 is the year of the rat because 1900
% 12 is 4 . Listing 3.10 gives a program that prompts the user to enter a year and displays the
animal for the year.
L ISTING 3.10 ChineseZodiac.java
1 import java.util.Scanner;
2
3 public class ChineseZodiac {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 System.out.print( "Enter a year: " );
8
enter year
int year = input.nextInt();
9
10
determine Zodiac sign
switch (year % 12 ) {
11
case 0 : System.out.println( "monkey" ); break ;
12
case 1 : System.out.println( "rooster" ); break ;
13
case 2 : System.out.println( "dog" ); break ;
14
case 3 : System.out.println( "pig" ); break ;
15
case 4 : System.out.println( "rat" ); break ;
16
case 5 : System.out.println( "ox" ); break ;
17
case 6 : System.out.println( "tiger" ); break ;
18
case 7 : System.out.println( "rabbit" ); break ;
19
case 8 : System.out.println( "dragon" ); break ;
20
case 9 : System.out.println( "snake" ); break ;
21
case 10 : System.out.println( "horse" ); break ;
22
case 11 : System.out.println( "sheep" );
23 }
24 }
25 }
Enter a year:
rabbit
1963
 
 
Search WWH ::




Custom Search