Some of the programs from the preceding lessons have been written without any flexibility. To change any of the data values in the programs, it is necessary to change the variable initializations, recompile the program, and run it again. Sometimes prompting the user for a value and then processing the data is more efficient and convenient.
-
However, accepting user input in Java can be complex. Throughout this curriculum, we will use the Scanner
class to make processing input easier and less tedious.
Just as the System class provides System.out
for output, there is an object for input, System.in
. Unfortunately, Java’s System.in
object does not directly support convenient methods for reading numbers and strings. We need to have a class sitting between the System.in
object and ourselves to filter what comes through. This is what the Scanner
class does.
- Scanner is part of the java.util package, so we need to start off by adding the Scanner class to our import section.
import java.util.Scanner;
- Next, we create our Scanner object and pass in the System.in object.
Scanner in = new Scanner(System.in);
This tells the Scanner to look at the System.in object for all of its input. In Student Lesson A13, we will learn how to change the object we pass to the Scanner so that we can read the data stored in text files.
- Here are some example statements:
When the statement num1 = in.nextInt()
is encountered, the program pauses until an appropriate value is entered on the keyboard.
Any whitespace (spaces, tabs, newline) will separate input values. When reading values, whitespace keystrokes are ignored.
- When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example:
System.out.print("Enter an integer --> ");
number = in.nextInt();