/* * Lab 1. Practice writing a simple Java program * with basic I/O and conditional logic * * This is one possible solution to this program. * * name: CS 112 Course Staff */ import java.util.*; public class Greetings { 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); System.out.print("\nPlease enter your first name: "); String name = scan.next(); System.out.println("Hello " + name + ", Welcome to CS112!!!"); System.out.print("How old are you " + name + "? "); int age = scan.nextInt(); // Once you are done with user input you can close the connection // to the Scanner. scan.close(); // Declare the string to be used to create the insult. // 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 multiway decision (if-else if-...) instead // of separate if statements. // // What would happen if we used separate if statements instead? // Would the logic be correct? // 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 += "!!!"; System.out.println(insult); // Close the connection scan.close(); } // main }