Greet2.java

Download this source file

/* A simple program to display a friendly greeting.  This stand-alone
 * non-GUI Java program demonstrates keyboard input the easy way, using the
 * new Java5 "Scanner" class.  It shows checking for and reading in both
 * a String and an int.  (Left as an exercise: test if user enters:
 *   name, age
 * and if so, remote the trailing comma from name.)
 *
 * Written by Wayne Pollock, Tampa, FL USA, 2005.
 */

import java.util.Scanner;

class Greet2
{

   public static void main ( String [] args )
   {
	  Scanner in = new Scanner( System.in );
	  String name = "Anonymous";
	  int age = Integer.MAX_VALUE;

	  System.out.print( "Please enter your first name and age: " );

      if ( in.hasNext() )
         name = in.next();

      if ( in.hasNextInt() )
         age = in.nextInt();

	  System.out.println( "\nHowdy " + name + "!" );

	  if ( age == Integer.MAX_VALUE || age < 1 )
	     System.out.println( "That's not a valid age!" );
	  else if ( age < 6 )
         System.out.println( "How adorable!" );
      else if ( age < 10 )
	     System.out.println( "My how you've grown!" );
	  else if ( age < 13 )
	     System.out.println( "You're all grown up!" );
	  else if ( age < 21 )
	     System.out.println( "Hey, dude!" );
	  else if ( age < 40 )
	     System.out.println( "Have a great day!" );
	  else
	     System.out.println( "My, how young you look!" );

   }  // End of main

}  // End of class Greet2