Console input and formatted output

Java · Essentials · 8 min

Small interactive programs and command-line tools need to read input and present results clearly.

For output you already know System.out.println. For aligned or rounded output, use printf-style formatting: System.out.printf("%-10s %6.2f%n", name, price);.

Common format specifiers:

  • %s any value (calls toString), %d integers, %f floating point.
  • %.2f two decimals; %8d right-aligned in 8 columns; %-10s left-aligned.
  • %n the platform line separator, %% a literal percent sign.

The same patterns work in String.format(...) and "...".formatted(...) when you need the string instead of printing it.

For input, the simplest tool is java.util.Scanner. Wrap System.in once and read tokens or lines: nextLine(), nextInt(), hasNextInt(). A classic gotcha: nextInt() leaves the newline in the buffer, so a following nextLine() returns an empty string. Reading everything with nextLine() and parsing with Integer.parseInt avoids that.

For large inputs (competitive programming, piping big files), Scanner is slow. Use BufferedReader:

var in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) { ... }

readLine() returns null at end of input (Ctrl+D on Unix, Ctrl+Z on Windows, or the end of a piped file).

Command-line arguments (args) are another input channel; prefer them for options like file names, and standard input for streams of data.

Example

import java.util.Scanner;

public class Tip {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Bill amount: ");
        double bill = Double.parseDouble(in.nextLine().strip());
        System.out.print("Tip percent: ");
        int pct = Integer.parseInt(in.nextLine().strip());

        double tip = bill * pct / 100.0;
        System.out.printf("%-6s %8.2f%n", "Bill", bill);
        System.out.printf("%-6s %8.2f (%d%%)%n", "Tip", tip, pct);
        System.out.printf("%-6s %8.2f%n", "Total", bill + tip);
    }
}
// Bill amount: 42.5
// Tip percent: 15
// Bill      42.50
// Tip        6.38 (15%)
// Total     48.88

Remember

  • printf/formatted with %s %d %.2f %n give precise output
  • Reading whole lines and parsing them avoids Scanner's leftover-newline trap
  • Use BufferedReader for fast line-by-line input; readLine() returns null at end

Watch out for

  • Calling nextInt() then nextLine() and getting an empty line.

Check yourself

  1. What does `String.format("%5.1f|", 3.14159)` produce?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Formatter.html

Builds on

Unlocks

Nothing builds on this yet.