Input and Output in Java

Reading from the keyboard and writing to the console, with the Scanner pitfall that catches almost every beginner.

Writing output

System.out.print("No line break. ");
System.out.println("With a line break.");
System.out.printf("%s scored %d marks (%.2f%%)%n", "Ravi", 87, 87.0);
FormatMeaning
%sAny value, converted with toString
%dWhole number
%fDecimal, %.2f for two places
%nPlatform line separator, preferred over a literal newline
%%A literal percent sign

System.err writes to the error stream. Keep diagnostics there so ordinary output stays clean when it is redirected.

Reading input with Scanner

import java.util.Scanner;

public class Enrolment {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Name: ");
        String name = in.nextLine();

        System.out.print("Age: ");
        int age = in.nextInt();

        System.out.printf("%s is %d years old.%n", name, age);
    }
}

The nextInt then nextLine trap

This is the single most common beginner bug in Java input.

int age = in.nextInt();      // reads the digits, leaves the line break behind
String city = in.nextLine(); // consumes that leftover break, returns ""

nextInt stops at the end of the number and does not consume the line break that follows it. The next nextLine therefore reads an empty remainder. Two reliable fixes:

// Option 1: consume the rest of the line explicitly
int age = in.nextInt();
in.nextLine();
String city = in.nextLine();

// Option 2: read every line as text and convert yourself
int age = Integer.parseInt(in.nextLine().trim());
String city = in.nextLine();

The second option is more predictable and is the habit worth forming.

Validating input

Scanner in = new Scanner(System.in);
int quantity;

while (true) {
    System.out.print("Quantity: ");
    String line = in.nextLine().trim();
    try {
        quantity = Integer.parseInt(line);
        if (quantity > 0) {
            break;
        }
        System.out.println("Please enter a positive number.");
    } catch (NumberFormatException e) {
        System.out.println("That is not a whole number.");
    }
}

Reading with BufferedReader

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BulkInput {

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String line;
        int lines = 0;
        while ((line = reader.readLine()) != null && !line.isBlank()) {
            lines++;
        }
        System.out.println("Lines read: " + lines);
    }
}

Scanner compared with BufferedReader

AspectScannerBufferedReader
ParsingBuilt in, token by tokenText only, parse yourself
SpeedSlowerFaster for large input
Checked exceptionsNone to handleIOException must be handled
Best forSmall interactive programsBulk input

Common mistakes

  • Mixing nextInt and nextLine without accounting for the leftover line break.
  • Creating several Scanner objects over System.in. One is enough, and buffering makes extras unreliable.
  • Closing a Scanner wrapped around System.in, which closes standard input for the rest of the program.
  • Assuming input is well formed and letting InputMismatchException end the program.

Best practices

  • Read whole lines and convert them yourself. It removes an entire class of bug.
  • Validate at the boundary and loop until the value is acceptable.
  • Use printf when output alignment matters.

Practice

  1. Write a program that reads a name and three marks and prints the average to two decimal places.
  2. Explain, in terms of the input buffer, why a nextLine after nextInt can return an empty string.
  3. Convert a Scanner based reader into a BufferedReader based one and state which exception you now have to handle.

Conclusion

Console input is simple once you accept that a Scanner reads tokens, not lines. Read lines, parse deliberately, and validate before using the value.

Topics #Beginner #Java
Written by Lorens Mishra

Default administrator account created by the installer.

Continue reading

All Java notes →
Java

Introduction to Java

Java is a statically typed, object oriented language that compiles to bytecode and runs on a virtual machine, which is what makes it portable.

Read more

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.