In this activity, we write a class to read input from the keyboard.
In addition to the Solution document, the project for this activity contains two classes:
The class Greeter is to have a method run, containing a loop which repeatedly prompts the user for their name and prints the message:
I am very pleased to meet you, X
whereX stands for the name typed in by the user.
If the user types Bye at the prompt the loop should terminate.
Your run method should make use of a class called Scanner which we describe below.
The project will not compile at this stage, so do not try to run it.
Before Java 5.0 you would read text from the keyboard by using code similar to the following:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Please enter your input");
String input = br.readLine();
Java 5.0 introduced a versatile new class Scanner which offers an alternative way of reading keyboard input. Using Scanner, the code above can be replaced with the following.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your input");
String input = sc.nextLine();
Scanner also takes care of any exceptions that may occur, so we do not have to do anything about exception handling.
Open the class Greeter and add code where indicated. Note that Scanner is in the package java.util rather than java.io. Greeter already contains the necessary import statement, but note also that it is easy to fix missing import statements in NetBeans by right-clicking in a source file and selecting 'Fix Imports'.
When you have made all the additions, run the project to test what you have written. When the program is executed an Output window will open at the bottom of the main NetBeans window. Enter a name or Bye in the output window and press Return. The response will appear in the Output window.