132k views
4 votes
In Java please.

The Chinese animal zodiac is a repeating cycle of 12 years, with each year being represented by an animal and its related attributes. Traditionally these zodiac animals were used to date the years. In order, the 12 animals are: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. Each year is associated with a zodiac animal. 2019 is the year of the Pig, 2020 is the year of Rat, 2021 will be the year of Ox
1. Use direct access method to implement the method YearToAnimalZodiac().

User Metadings
by
3.8k points

2 Answers

6 votes

Answer:

String[] animals = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"};

User Jazzurro
by
4.4k points
0 votes

Answer:

See explaination

Step-by-step explanation:

public class YearToAnimal {

static void yearToAnimalZodiac(int year){

String[] animals = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"};

int baseYear = 2020;

int index = (year - baseYear) % 12;

// in case of negative index, change it to positive

if(index < 0)

index = 12 + index;

System.out.println(year + ": " + animals[index]);

}

// some test cases

public static void main(String[] args) {

yearToAnimalZodiac(2020);

yearToAnimalZodiac(2021);

yearToAnimalZodiac(2019);

yearToAnimalZodiac(2009);

yearToAnimalZodiac(2008);

yearToAnimalZodiac(2007);

}

}

User Simon Alford
by
4.3k points