Learning JAVA through Games - Chapter 2 exercise 3
Exercise: Write a program that checks if the user is underage. If they are, then the program
should tell them not to go to the bar. If they are over 21, then the program should
print that they are allowed to go to the bar, but they should drink responsibly.
I went the more complicated route by asking for the users birthday instead of just asking if they were 21, but I learned more this way. I had to look up how to get the current year, month and day. I only ask for the month / day of the birthday if it's necessary and if it's their birthday they get a special message.
import java.util.*;
public class Test21 {
public static void main(String[] args) {
String output = "";
int year = Calendar.getInstance().get(Calendar.YEAR);
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your birth year(ex: 1985): ");
int birthYear = keyboard.nextInt();
if ((year-birthYear) < 21){
output = "Don't go to the bar";
}
else if ((year-birthYear) > 21){
output = "Drink responsibly.";
}
else{
int month = Calendar.getInstance().get(Calendar.MONTH);
System.out.print("Enter your birth month(ex: 10): ");
int birthMonth = keyboard.nextInt();
if (month+1 < birthMonth){
output = "Don't go to the bar";
}
else if (month+1 > birthMonth){
output = "Drink responsibly.";
}
else{
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
System.out.print("Enter your birth day(ex: 30): ");
int birthDay = keyboard.nextInt();
if (day < birthDay){
output = "Don't go to the bar";
}
else if (day > birthDay){
output = "Drink responsibly.";
}
else{
output = "HAPPY 21ST BIRTHDAY!! Go to the bar.";
}
}
}
System.out.println(output);
}
}

No comments:
Post a Comment