import java.util.Scanner; /* * Lab 2, Practice writing a simple Java program * - basic I/O and Conditional Logic * * This is one possible solution to this program. * * name: CS 112 Course Staff */ public class Greetings { static final int CUTOFF_YOUTH = 11; static final int CUTOFF_TEEN = 18; static final int LEGAL_AGE = 21; static final int CUTOFF_Y_ADULT = 30; static final int CUTOFF_M_AGE = 40; static final int CUTOFF_OLD = 50; public static void main( String [] args ) { // Declare a reference to an instance of the Scanner class. // This creates the necessary connection to the keyboard // as our input device. Scanner scan = new Scanner( System.in ); int age; System.out.print( "\nPlease enter your name: " ); String name = scan.nextLine(); System.out.print( "Hello " + name + ", Welcome to CS112!!!\nHow old are you " + name + "? " ); age = scan.nextInt(); // Declare the string to be used to create the unsult... // Note the use of the + operator to perform string concatenation. // This allows us to 'build' our insult as the program executes. // String insult = "Wow " + name + ", you "; // Following is the conditional logic that allows us the create // the insult we want, based on the age that was entered. // // Note the use of a multiple conditional construct instead of a series // of single conditional statements.... // // What would happen if we removed the else keyword? // Would the conditional structure execute the same? // if ( age <= 0 ) insult += "are an idiot who does not pay attention to directions"; else if ( age < CUTOFF_YOUTH ) insult += "are still sweet, for the moment"; else if ( age < CUTOFF_TEEN ) insult += "are such a dweeb"; else if ( age < LEGAL_AGE ) { int diff = 21-age; insult += "have " + diff + " year"; if (diff > 1) insult += "s"; insult += " to go"; } else if ( LEGAL_AGE == 21 ) insult += "just made it"; else if ( age < CUTOFF_Y_ADULT ) { int diff = 30-age; insult += "have only " + diff + " good year"; if (diff > 1) insult += "s"; insult += " left"; } else if ( age < CUTOFF_M_AGE ) insult += "are in a sorry state"; else if ( age < CUTOFF_OLD ) insult += "must be miserable"; else insult = "yikes"; insult += "!!!"; // Output the insult!!! System.out.println( insult ); } // main }