5.11 Reading User Input

This lesson builds a small Java program that reads input from the keyboard. The class we use is Scanner from java.util.Scanner. We instantiate it with Scanner scanner = new Scanner(System.in);: new creates a fresh instance and System.in is the standard input stream.

We then prompt the user with System.out.println("Enter your name:"); and capture the reply with String name = scanner.nextLine();. The method nextLine() blocks until the user types something and presses Enter; the typed string is then assigned to the name variable. Printing "Your name is " + name echoes it back.

Reading an int and computing an age

  • Prompt with "Enter your birth year:".
  • Read an integer with int birthYear = scanner.nextInt();.
  • Compute the age with int age = 2021 - birthYear; and concatenate the message "You are " + age + " years old".
  • End with scanner.close(); to release the underlying stream.

One subtle detail: after nextInt() the cursor stays on the same line, so a follow-up nextLine() reads an empty string. Calling an extra scanner.nextLine(); after nextInt() consumes that leftover newline. With these few lines you have a Java program that talks to its user instead of staying silent.

Summary

This lesson covers how to read user input in Java using the Scanner class. You'll learn to create a Scanner object tied to System.in, capture text with nextLine() and integers with nextInt(), and use that data in your program. Practical examples demonstrate reading a user's name and birth year, calculating age, and displaying results on the screen.

Key points

  • Import and instantiate the Scanner class: Scanner scanner = new Scanner(System.in)
  • Use scanner.nextLine() to read text input (strings) from the user
  • Use scanner.nextInt() to read numeric input (integers) from the user
  • Always close the Scanner with scanner.close() when finished to release system resources
  • Combine user input with calculations and conditional logic to build interactive programs
  • Input operations pause program execution until the user presses Enter

FAQ

What is the difference between nextLine() and nextInt()?

nextLine() reads an entire line of text including spaces, while nextInt() reads a single integer. Use nextLine() for names and nextInt() for numeric values like birth years.

Why do we need to close the Scanner?

Closing the Scanner properly releases system resources and prevents memory leaks. Always call scanner.close() when you're done reading user input.

Can I use Scanner to read input from a file instead of the keyboard?

Yes, Scanner can be instantiated with a File object: Scanner scanner = new Scanner(new File("filename.txt")) to read from files instead of System.in.