Free Ebook cover Java for Beginners: A Complete Introduction to Programming with Java

Java for Beginners: A Complete Introduction to Programming with Java

New course

10 pages

Working with Input and Output in Java Console Programs

Capítulo 4

Estimated reading time: 5 minutes

+ Exercise

Why Console Input and Output Matter

Console programs interact with users through text: you print prompts (output) and read what the user types (input). In Java, a common beginner-friendly way to read console input is the Scanner class. You will typically: import the class, create a Scanner connected to System.in, read values (text and numbers), then print results—often with formatting.

Importing the Scanner Library

Scanner lives in the java.util package, so you must import it at the top of your file.

import java.util.Scanner;

If you forget this import, you will usually see an error like “Scanner cannot be resolved to a type”.

Creating a Scanner

Create one Scanner object for reading from the keyboard (standard input). A common pattern is to create it inside main.

import java.util.Scanner; public class Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         // read input here         scanner.close();     } }

Note: In small learning programs, calling scanner.close() is fine. In larger applications, closing System.in can affect other input later, but for single-run console exercises it is acceptable.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

Printing Output: Prompts and Formatted Results

Basic printing

Use System.out.print to keep the cursor on the same line, and System.out.println to move to the next line.

System.out.print("Enter your name: "); System.out.println("Thanks!");

Formatted printing with printf

System.out.printf lets you insert values into a format string. Common placeholders include %s for strings, %d for integers, and %.2f for decimals with 2 digits after the decimal point.

String name = "Sam"; int count = 3; double price = 12.5; System.out.printf("Hello %s, you bought %d items. Total: $%.2f%n", name, count, price);

%n prints a platform-independent newline.

Reading Strings

The two most used string-reading methods are:

  • next(): reads one “token” (stops at whitespace). Good for single words.
  • nextLine(): reads the entire line (including spaces) until Enter is pressed. Good for full names or sentences.
System.out.print("Enter a one-word username: "); String username = scanner.next(); System.out.print("Enter your full name: "); scanner.nextLine(); // consume leftover newline if needed (explained later) String fullName = scanner.nextLine();

In many programs you will prefer nextLine() for user-friendly input because it allows spaces.

Reading Numbers (int and double)

Scanner can parse numeric input directly.

  • nextInt() reads an integer (e.g., 10, -3).
  • nextDouble() reads a decimal number (e.g., 3.14).
System.out.print("Enter an integer: "); int a = scanner.nextInt(); System.out.print("Enter a decimal number: "); double b = scanner.nextDouble();

If the user types something that cannot be parsed (like “ten”), Scanner throws an InputMismatchException. In beginner projects, you can assume correct input; later you can add validation loops.

Guided Project: Name + Two Numbers, Friendly Output + Calculation

Goal: ask the user for their name and two numbers, then print a friendly message and a calculated result. This project also demonstrates a common pitfall: mixing numeric reads with nextLine().

Step 1: Set up imports and Scanner

import java.util.Scanner; public class Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         // steps go here         scanner.close();     } }

Step 2: Ask for the name (use nextLine)

Using nextLine() allows the user to type a full name with spaces.

System.out.print("What is your name? "); String name = scanner.nextLine();

Step 3: Ask for two numbers

Read two numbers. Here we will use double so the user can enter either whole numbers or decimals.

System.out.print("Enter the first number: "); double num1 = scanner.nextDouble(); System.out.print("Enter the second number: "); double num2 = scanner.nextDouble();

Step 4: Compute and print formatted results

Compute a result (for example, the sum) and print a friendly message using printf.

double sum = num1 + num2; System.out.printf("Hi %s! The sum of %.2f and %.2f is %.2f.%n", name, num1, num2, sum);

Full project code (ready to run)

import java.util.Scanner; public class Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         System.out.print("What is your name? ");         String name = scanner.nextLine();         System.out.print("Enter the first number: ");         double num1 = scanner.nextDouble();         System.out.print("Enter the second number: ");         double num2 = scanner.nextDouble();         double sum = num1 + num2;         System.out.printf("Hi %s! The sum of %.2f and %.2f is %.2f.%n", name, num1, num2, sum);         scanner.close();     } }

Common Pitfall: Mixing nextLine() with Numeric Reads

A frequent issue happens when you read a number with nextInt() or nextDouble() and then try to read a line of text with nextLine(). The numeric methods read the number but leave the newline (the Enter key) in the input buffer. Then nextLine() immediately reads that leftover newline and returns an empty string.

Example of the problem

System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.print("Enter your full name: "); String fullName = scanner.nextLine(); // often becomes "" (empty) System.out.println("Name: " + fullName);

Fix: Consume the leftover newline

After reading a number, call nextLine() once to consume the remaining newline, then call it again to read the real text.

System.out.print("Enter your age: "); int age = scanner.nextInt(); scanner.nextLine(); // consume leftover newline System.out.print("Enter your full name: "); String fullName = scanner.nextLine(); System.out.printf("Age: %d, Name: %s%n", age, fullName);

Alternative approach: Read everything with nextLine and parse

Another reliable pattern is to read user input as strings using nextLine() and then convert to numbers. This avoids the leftover newline issue entirely.

System.out.print("Enter the first number: "); double num1 = Double.parseDouble(scanner.nextLine()); System.out.print("Enter the second number: "); double num2 = Double.parseDouble(scanner.nextLine());

If the user types invalid input, parsing methods like Double.parseDouble throw a NumberFormatException. You can later add checks and re-prompting to make the program more robust.

Now answer the exercise about the content:

After reading a number with Scanner (e.g., nextInt or nextDouble), why might a following nextLine() return an empty string, and what is the typical fix?

You are right! Congratulations, now go to the next page

You missed! Try again.

Numeric methods read the value but leave the newline in the input buffer. A following nextLine() may consume that newline and return an empty string. Call nextLine() once to clear it, then read the real line.

Next chapter

Conditional Logic with if, else if, and switch in Java

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.