CH3 – The Scanner Class

  1. Create a new class Echo.
  2. Type the following code and save Echo.java.
import java.util.Scanner;

public class Echo {
  public static void main(String[] args){
  }
}
  1. Compile the program.
javac Echo.java
  1. Fix any errors and open the file. You compiled the program simply to ensure it compiled. There is nothing to run at this point.
  2. Add the following code.
import java.util.Scanner;

public class Echo {
  public static void main(String[] args){
    String line;
    Scanner in = new Scanner(System.in);
    System.out.print("Type something: ");
    line = in.nextline();
    System.out.println("You said: " + line);
    System.out.print("Type something else: ");
    line = in.nextLine();
    System.out.println("You also said: " + line);
  }
}
  1. Compile the program. If you typed it exactly as shown, the in.nextline should generate the following error.
Echo.java:8: error: cannot find symbol
    line = in.nextline();
             ^
  symbol:   method nextline()
  location: variable in of type Scanner
1 error
  1. Read the error and find its source before attempting to fix the error.
  2. Fix the line to in.nextLine and recompile.
  3. Run the program.

Although the Scanner class is good for a command line driven program and for teaching, you will rarely use this class in the real world. In reality, you would use a Graphical User Interface (GUI), a web programming construct such as a Java Servlet or Java Server Page (JSP), or you would use a command line parameter. Let’s modify this example to use a command line parameter.

  1. Modify the program to appear like the following. Change the class name to Echo2. When saving, be certain to rename the file to Echo2.java.
public class Echo2 {
  public static void main(String[] args){
    String line;
    line = args[0];
    System.out.println("You said: " + line);
    line = args[1];
    System.out.println("You also said: " + line);
 }
}
  1. Compile and then attempt running the program. You should receive the following error.
$ java Echo2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at Echo2.main(Echo2.java:4)

Although the authors haven’t discussed arrays yet, the reason for this error is that the program expects an array of two command line parameters. Instead pass the two parameters as follows.

$ java Echo2 Hello Goodbye
You said: Hello
You also said: Goodbye

For another tutorial on the Scanner class, refer to this video by LearningLad.