CSE 142 Lecture Notes: Interactive Programs With Scanner
CSE 142 Lecture Notes: Interactive Programs With Scanner
These lecture notes are copyright (C) Marty Stepp 2005. May not be rehosted, copied, sold, or
modified without Marty Stepp's expressed written permission. All rights reserved.
1
Interactive programs
We have written several programs that print output to
the console.
3
Scanner
Since System.in is not easy to use by itself, we will use
a second object of a type named Scanner to help.
Once we construct the Scanner object, we can ask it to read
various kinds of input from the console.
Example:
Scanner console = new Scanner(System.in);
4
Scanner as data source
Think of a Scanner like a faucet or showerhead that can
be attached to a source of 'water' (data). In our case,
the source of that data is System.in .
Like a faucet must be connected to a water source,
the Scanner must be connected to a data source
by writing (System.in) when constructing it.
5
Scanner methods
Methods of Scanner that we will use in this chapter:
Method Description
next() reads and returns next token as a String
nextDouble() reads and returns next token as a double
nextInt() reads and returns next token as an int
nextLine() reads and returns next entire line of input as
a String
6
Example Scanner usage
public class ReadSomeInput {
public static void main(String[] args) {
System.out.print("How old are you? ");
int age;
9
Consume input example
Example: If the following input from the user has been typed,
23 3.14 John Smith "Hello world"
45.2 19
The Scanner views it as a linear stream of data, like the following:
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
The Scanner positions its 'cursor' at the start of the user input:
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^
As we call the various next methods on the Scanner, the scanner
moves forward:
int x = console.nextInt(); // 23
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^
double pi = console.nextDouble(); // 3.14
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^
String word = console.next(); // "John"
23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19\n
^
10
Line-based input
The Scanner's nextLine method consumes and returns
an entire line of input as a String.
The Scanner moves its cursor from its current position until it
sees a \n new line character, and returns all text that was
found.
The new line character is consumed but not returned.
Example:
23 3.14 John Smith "Hello world"
45.2 19
int n = console.nextInt(); // 23
23\t3.14\nJoe\t"Hello world"\n\t\t45.2 19\n
^
double x = console.nextDouble(); // 3.14
23\t3.14\nJoe\t"Hello world"\n\t\t45.2 19\n
^