import java.util.Scanner; /* * Lab 2, Practice writing Methods * * name: CS 112 Course Staff */ public class Greetings2 { /* * This method prompts for a name and age and displays * a welcome message accordinglty */ public static void greetMe() { Scanner scan = new Scanner( System.in ); int age; String keepGreeting; do { 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(); System.out.println( insult( name, age ) ); System.out.print( "\nWould you like to issue another greeting (yes/no)? " ); keepGreeting = scan.next(); // Need to use this to read throg the newline character left on the input buffer // from the prior call to next() // Recall that each call to nextLine will stop at the first newline encountered scan.nextLine(); } while ( keepGreeting.equals("yes") ); // Note the use of calling the equals method on the String object } /* * This method forms a string based on the value * of the age argument. */ public static String insult( String name, int age ) { // Can also check that the parameter name is not passed a null value, // but not explicitly necessary as this method is not invoking any methods on name. // String insult = "Wow " + name + ", you "; if ( age <= 0 ) insult += "are an idiot who does not pay attention to directions"; else if ( age < 11 ) insult += "are still sweet, for the moment"; else if ( age < 18 ) insult += "are such a dweeb"; else if ( age < 21 ) { int diff = 21-age; insult += "have " + diff + " year"; if (diff > 1) insult += "s"; insult += " to go"; } else if ( age == 21 ) insult += "just made it"; else if ( age < 30 ) { int diff = 30-age; insult += "have only " + diff + " good year"; if (diff > 1) insult += "s"; insult += " left"; } else if ( age < 40 ) insult += "are in a sorry state"; else if ( age < 50 ) insult += "must be miserable"; else insult = "yikes"; insult += "!!!"; return( insult ); } /* * This method is the entry point of our program. * * This method should be used to call the individual methods * that have been written as specified in lab. * */ public static void main( String [] args ) { //the main method is just the entry point now //and acts as a driver to run your program. //by calling the appropriate method. greetMe(); } }