/* This program demonstrates the switch statement and a few String methods */ import java.util.Scanner; class JohnCena { public static void main(String [] args) { Scanner input = new Scanner(System.in); /* Here, we read in the day of the week as text, and print out the numeric equivalent. * We start off from Monday. So, Monday = 1, Tuesday = 2, ... * Also, the switch statement uses String.equals() internally, so the string have to match entirely * (including uppercase and lowercase letters, for a case to be triggered. "Monday" is not the same as "monday". */ System.out.println("Please enter the day of the week :"); String day = input.next(); // read in the day of the week as a String switch(day) { case "Monday" : System.out.println("Monday is 1"); break; //break statements prevent the cases from "falling through". case "Tuesday" : System.out.println("Tuesday is 2"); break; case "Wednesday" : System.out.println("Wednesday is 3"); break; case "Thursday" : System.out.println("Thursday is 4"); break; case "Friday" : System.out.println("Friday is 5"); break; case "Saturday" : System.out.println("Saturday is 6"); break; case "Sunday" : System.out.println("Sunday is 7"); break; default: System.out.println("Invalid entry."); //default case is triggered when the variable "day", doesn't match any of the above cases. } /* In this part of the program, we read in two strings as firstName and lastName, * and compare them to figure out which one is is first alphabetically. * We use the String.compareTo method, which goes through the two strings letter by letter, * subtracting the ASCII value of the second from the first, until a non zero value is encountered or * one or both of the strings terminates. */ /* And I figured out why the Scanner.nextLine() was all haywire. Yaay. * next(), or nextFoo() (nextInt(), nextDouble(), etc) do not consume whitespace. * nextLine() consumes the trailing newline, but not the preceding newline. * So, the newline after reading in the day of the week is still on the stream. * When we read in the next string, the nextLine() stops there. * Oracle is of the opinion that this is a feature, not a bug :P * So, we just read in the preceding newline into a dummy string and discard it. * That is what the next line does. * TL; DR: If you want to use nextLine(), and the previous read was anything other than a nextLine(), use the line below before you do any further reads. */ String junk = input.nextLine(); String firstName,lastName; System.out.println("Enter first name :"); firstName = input.nextLine(); System.out.println("Enter last name :"); lastName = input.nextLine(); // should be fairly self explanatory. if(firstName.compareTo(lastName)<0) System.out.println(firstName+" is alphabetically first."); else if(firstName.compareTo(lastName)>0) System.out.println(lastName+" is alphabetically first."); else System.out.println("You first name is the same as your last name."); } }