Source of TidyingUp.java


  1: import java.util.Scanner;

  3: /**
  4:  * Failure to tidy up leads to an embarrassing error
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class TidyingUp {

 10:     /**
 11:      * Run this program.
 12:      *
 13:      * @param args command lines arguments (ignored)
 14:      */
 15:     public static void main(String[] args) {
 16:         // introduce self
 17:         System.out.println("\n"
 18:                 + "Age and Name Reader\n"
 19:                 + "-------------------\n\n"
 20:                 + "This program (supposedly!) reads your age and name.\n");

 22:         // create variables
 23:         Scanner kbd = new Scanner(System.in);
 24:         int age;
 25:         String name;

 27:         // get age
 28:         System.out.print("What is your age? ");
 29:         age = kbd.nextInt();        // user presses Enter key HERE
 30:                                     // but computer doesn't read it
 31:         System.out.println();

 33:         // get name (?!?!)
 34:         System.out.print("What is your name? ");
 35:         name = kbd.nextLine();      // computer reads Enter key HERE
 36:                                     // thus doesn't let user enter their name
 37:         System.out.println();

 39:         // print message
 40:         System.out.println("Hi, " + name + "!");
 41:         System.out.println("You are " + age + " years old.");
 42:         System.out.println();

 44:         // try again
 45:         System.out.println("Sorry!  Let's try that again!");
 46:         System.out.println("...press enter...");
 47:         kbd.nextLine();
 48:         System.out.println();

 50:         // get age
 51:         System.out.print("What is your age? ");
 52:         age = kbd.nextInt();        // user presses Enter key HERE
 53:         kbd.nextLine();             // and computer tidies it away
 54:         System.out.println();

 56:         // get name (?!?!)
 57:         System.out.print("What is your name? ");
 58:         name = kbd.nextLine();      // computer has no enter key waiting here
 59:                                     // and so need to pause to get the name
 60:         System.out.println();

 62:         // print message
 63:         System.out.println("Hi, " + name + "!");
 64:         System.out.println("You are " + age + " years old.");
 65:         System.out.println();
 66:     }
 67: }