CCA Guide
Scanner

Scanner

Curated by Last modified: 1 min read

View Markdown

Scanner is a class in java.util, commonly used to read user input.

Initialization

import java.util.Scanner;

// Inside a method:
Scanner kb = new Scanner(System.in); // Standard input

Common methods

MethodReadsReturn type
nextInt()The next integer tokenint
next()The next token, delimited by whitespace by defaultString
nextLine()The rest of the current line, excluding the line separatorString

Mixing token and line input

After nextInt(), the remainder of the current line can still be waiting. If only a line separator remains, nextLine() consumes it and returns an empty string.

int age = kb.nextInt();
kb.nextLine(); // Discard the remainder of the number's line.
String name = kb.nextLine(); // Read the following line.

Correction to the original notes

System.in is standard input, rather than output. nextLine() excludes the newline from its returned value; it does not return the newline character itself. Only discard a line when that is what the input format requires.

Source: Scanner API.

Related: Strings and characters · Variables

Linked to this page