next up previous
Next: Example: initials of a Up: Unit 02 Previous: Example: initials of a

Input from the keyboard

In Java, there are many ways to read strings from input. The simplest one is to make use of the class Scanner, which is part of the java.util library and has been newly introduced in Java 5.0. Using this class, we can create an object to read input from the standard input channel System.in (typically, the keyboard), as follows:

Scanner scanner = new Scanner(System.in);
Then, we can use the nextLine() method of the Scanner class to get from standard input the next line (a sequence of characters delimited by a newline character), according to the following schema:

import java.util.Scanner;

public class KeyboardInput {
  public static void main (String[] args) {
    ...
    Scanner scanner = new Scanner(System.in);
    String inputString = scanner.nextLine();
    ...
    System.out.println(inputString);
    ...
  }
}

We can also read in a single word (i.e., a sequence of characters delimited by a whitespace character) by making use of the next() method of the Scanner class. We will see later that the Scanner class is also equipped with other methods to directly read various types of numbers from standard input.


next up previous
Next: Example: initials of a Up: Unit 02 Previous: Example: initials of a