# Scanner

Source: https://cca.twango.dev/AP-Computer-Science/scanner

# Scanner

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

## Initialization

```java
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**.

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

> [!note] 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](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html).

Related: [[strings-and-characters|Strings and characters]] · [[variables|Variables]]
