Source of Greeting.java


  2: import java.util.Scanner;

  4: /**
  5:  * This program illustrates if-else controls nested inside other if-else
  6:  * controls. It greets the user with a message appropriate to the time of day.
  7:  *
  8:  * @author Mark Young (A00000000)
  9:  */
 10: public class Greeting {

 12:     public static void main(String[] args) {
 13:         // create variables
 14:         Scanner kbd = new Scanner(System.in);
 15:         int hour;
 16:         String amPM;

 18:         // introduce yourself
 19:         System.out.print("\n\n"
 20:                 + "This program prints a greeting based on the time of day.\n"
 21:                 + "When asked, enter the hour, a space, and either AM or PM,\n"
 22:                 + "like this: 11 AM or 4 PM\n\n");

 24:         // get the time
 25:         System.out.print("What time is it? ");
 26:         hour = kbd.nextInt();
 27:         amPM = kbd.next().toLowerCase();  // change AM to am; PM to pm
 28:         kbd.nextLine();

 30:         // correct 12 to 0 (e.g. 12 pm is afternoon instead of evening).
 31:         // This way, the morning/afternoon runs from 0 to 11 instead of that
 32:         // weird 12, 1, 2, 3, ..., 11 ordering. 
 33:         if (hour == 12) {
 34:             hour = 0;
 35:         }

 37:         // print the appropriate message
 38:         if (amPM.equals("pm")) {
 39:             if (hour < 6) {
 40:                 System.out.println("Good afternoon!");
 41:             } else {
 42:                 System.out.println("Good evening!");
 43:             }
 44:         } else {
 45:             if (hour > 6) {
 46:                 System.out.println("Good morning!");
 47:             } else {
 48:                 System.out.println("Good grief!");
 49:             }
 50:         }
 51:     }

 53: }