Search⌘ K
AI Features

Interactive Programs with Scanner

Understand how to use the java.util.Scanner class to read user input from the console. Explore methods for capturing text and numeric data, address common input issues like the dangling newline, and learn to build interactive loops that respond to user choices.

Up until now, our programs have relied on hard-coded values defined directly in the source code. While this works for learning syntax, real-world software needs to be dynamic. It must respond to users, process new data, and behave differently based on external input.

To bridge the gap between our code and the user, we use the Scanner class, which allows us to read input directly from the console during execution. This capability transforms static scripts into interactive tools.

The Scanner class and text input

Java provides the java.util.Scanner class to read text and numbers from various input sources, including files and the command line. To read from the console, we connect the scanner to System.in, which represents the standard input stream (the keyboard). ...