Getting Input From the User#

Commands for getting input from the user are not built-in to Java. One of the simplest ways to get input is to use the Scanner library. You must first import the library, then make an object of type Scanner, and use dot messages to make input happen. This is the same OOP pattern as you would have seen with Python, and described in the previous section. Here are some examples of getting input from a user:

1.	 import java.util.Scanner;
2.	 public static void main(String[] args) {
3.	      Scanner keyboard = new Scanner(System.in);
4.	      int favNum;
5.	      System.out.print("Please enter your favorite integer: ");
6.	      favNum = keyboard.nextInt();
7.	     
8.	      String name;
9.	      keyboard.nextLine(); //Clear the Enter key
10.	      System.out.println("Please enter your name: ");
11.	      name = keyboard.nextLine();
12.	  
13.	      System.out.println("Hi " + name + 
14.	              ". Your favorite number is " + favNum);
15.	 }

Notice five things, in particular:

  1. An input object must be created, in line 3, with the new operator.

  2. Dot notation is used to send messages to the input object, in lines 6, 9, and 11.

  3. Different input methods must be used with different data types, for example contrast lines 6 and 11.

  4. Every character that is typed is going to be retrieved, including the Enter key character or characters. We need an extra line in the code to clear out the characters left after reading an integer, and before we read the name, in line 9. If we omit this line of code, then the name will read as the empty string.

  5. If we want to access the information that we read, then we need to store it into memory by assigning it to a variable. Contrast line 9 (no assignment because we don’t need that information) and line 11 (assignment to the variable name because we are going to print it later).