3️⃣

7.3 Practice

Chapter Table of Contents

⚒️
Ch. 7 Other Selection Structures

Section Table of Contents

Practice

Month

Prompt the user for a number from 1 to 12. Using a switch, print the month that corresponds with that number. If the number is not from 1 to 12, print an error message.

Chinese Zodiac

Adapted from Listing 3.9 from Introduction to Java Programming (Comprehensive), 10th ed. by Y. Daniel Liang

Prompt the user for their birth year. Using a switch, print their zodiac sign. Hint: Zodiac signs repeat every 12 years. Order of zodiac signs: monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, sheep.

Enhanced Calculator

Create a program called Calculator which has the same functionality as the one in the switch example, except with more features!

Here's where we're going to make use of the modulus operator which gives the remainder of a division problem. Add the % operator as one possible option for the user to choose and utilize.

You should also change the operator choices. For example, instead of prompting the user for "add" or "subtract", prompt them for the characters '+' and '-'. Note: You can assume that the operator given by the user is the first character in the line, since there is no nextChar() method for Scanner.

Max

Create a program called Max, which prompts the user to enter 2 numbers. Use the ternary operator to assign a value to a variable max, and then print the max.

💡

Note: In the real world, we would not figure out the maximum or minimum of 2 numbers from scratch. Instead, you should use the methods Math.max(a, b) and Math.min(a, b), which return the max/min of 2 numbers a, b.

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.