AP Computer Science Java: Lesson 1.4a
Input and Output - Keyboard Input

Lesson 1.4a - Keyboard Input
Purpose: To learn how to input data into variables using the Scanner class methods

Program Input
Displaying information is only part of the programming process. The part that typically comes before that is input. In Java, there are many ways to perform console or keyboard input. This is typically done by way of a class. In our case, we will use the Scanner class. The Scanner class has methods which provide for the ability to input a value from the keyboard, then store that value into an appropriate variable. This could be an int, a double, even a String.

First we must declare a Scanner class input variable as follows:

Scanner console = new Scanner(System.in); //console is a Scanner variable and can accept keyboard input

Below is a table of the Scanner input methods.

Scanner Class Input Methods
Input Type Method Name Example of use in code
int number = console.nextInt();
double value = console.nextDouble();
char letter = console.next().charAt(0);
String (single word)
String word = console.next();
String (multiple words)
String sentence = console.nextLine();

Take note that the word following read in each method is to be capitalized, in keeping with Java conventions. Also recognize that there are two methods for reading a String. The next() method will not read beyond a single word and stops reading once it sees a space. So be sure to use nextLine() when a string may contain spaces.


© DanShuster.com