AP-Computer-Science ScienceAP
Scanner Scanner
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
| Method | Reads | Return type |
|---|---|---|
nextInt() | The next integer token | int |
next() | The next token, delimited by whitespace by default | String |
nextLine() | The rest of the current line, excluding the line separator | String |
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.inis 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