Advanced Search

Browse by Discipline

Scientific Societies

E-print Alerts

Add E-prints

E-print Network

  Advanced Search  

java.util.Scanner CSCI 136: Fall 2009

Summary: java.util.Scanner
CSCI 136: Fall 2009
The Scanner
A Scanner object can parse user input entered on the console or from a file. A Scanner breaks its input
into separate tokens (which are typically separated by white space), and then returns them one at a
time. The scanner provides methods to convert the tokens into values of different types. For example,
this code reads two numbers from the console and prints their sum:
Scanner in = new Scanner(System.in);
int i = in.nextInt();
int j = in.nextInt();
The scanner also provides methods to test whether there is any input left, and if there is, what type
of token appears next. This functionality is provided through methods like hasNextInt, hasNextDouble.
For example, the following code reads integers and adds them up until there is no more input or a non-
numeric token is encountered:
Scanner in = new Scanner(System.in);
int sum = 0;
while (in.hasNextInt()) {
sum += in.nextInt();


Source: Albrecht, Jeannie - Computer Science Department, Williams College


Collections: Computer Technologies and Information Sciences