Programming and Java Fundamentals

Reading User Input

ReadingPreview

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

So far, most of the values in our programs have been written directly inside the source code.

String studentName = "Sakib";
int age = 20;

These are hard-coded values.

However, in an interactive program, the user can provide data while the program is running.

For example:

  • Name
  • Age
  • Mark
  • Product quantity
  • Search text
  • Course selection

In a console-based Java application, we can use Scanner to read keyboard input.

In this lesson, we will learn:

  • What Scanner is
  • How to import and create a Scanner
  • How to display a prompt to the user
  • How to read input using nextLine()
  • How to parse numbers from text input
  • How to read multiple inputs
  • The common nextInt() and nextLine() problem
  • Basic input validation
  • How to close a Scanner

Learning Objectives

After completing this lesson, you will be able to:

  • Read user input from the console
  • Import and create a Scanner
  • Use nextLine() to read a full line
  • Normalize String input
  • Parse int and double values from String input
  • Read multiple inputs sequentially
  • Understand the problem that can occur when mixing nextInt() and nextLine()
  • Perform basic input validation
  • Write a simple interactive console program

What Is User Input?

User input is data provided by the user while a program is running.

Example:

Enter your name: Sakib
Enter your age: 20

Here:

Sakib
20

are values provided by the user.

The program can store and process these values.

Hard-Coded Value vs. User Input

Hard-coded:

String name = "Sakib";

The value is fixed inside the source code.

User input:

String name = scanner.nextLine();

Here, the user provides the value while the program is running.

What Is Scanner?

Scanner is a class from the Java standard library that helps read input.

For keyboard input, we use Scanner with:

System.in

System.in is the standard input stream.

Importing Scanner

Scanner is a class from the java.util package.

Write this at the beginning of the source file:

import java.util.Scanner;

Basic structure:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

    }
}

Creating a Scanner

To read keyboard input:

Scanner scanner =
        new Scanner(System.in);

Here:

  • Scanner — type
  • scanner — variable name
  • new Scanner(...) — creates a Scanner object
  • System.in — keyboard input source

First Input Program

import java.util.Scanner;

public class Main {

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

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

        String name =
                scanner.nextLine();

        System.out.println(
                "Hello, " + name
        );

        scanner.close();
    }
}

Possible interaction:

Enter your name: Sakib
Hello, Sakib

Displaying a Prompt

You should clearly tell the user what input is expected.

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

print() does not create a new line.

Therefore, the interaction looks like:

Enter your name: Sakib

A clear prompt helps reduce invalid input.

Better:

Enter your age in years:

Compared with:

Input:

nextLine()

To read an entire line:

String value =
        scanner.nextLine();

Input:

Md Samiul Alim Sakib

Stored value:

Md Samiul Alim Sakib

The entire line, including spaces, is read.

Normalizing Input

User input may contain extra whitespace at the beginning or end.

String name =
        scanner
                .nextLine()
                .strip();

Input:

   Sakib

Stored value:

Sakib

For text input, .strip() is often useful.

Reading Numeric Input

nextLine() always returns text.

Suppose the user enters:

20

We can first read it as a String:

String ageText =
        scanner.nextLine();

Then parse it into an int:

int age =
        Integer.parseInt(
                ageText.strip()
        );

Integer Input Example

System.out.print(
        "Enter your age: "
);

int age =
        Integer.parseInt(
                scanner
                        .nextLine()
                        .strip()
        );

System.out.println(
        "Next year you will be "
        + (age + 1)
);

Interaction:

Enter your age: 20
Next year you will be 21

Decimal Input

For decimal input:

System.out.print(
        "Enter course price: "
);

double price =
        Double.parseDouble(
                scanner
                        .nextLine()
                        .strip()
        );

Input:

4990.50

Variable:

price = 4990.5

Boolean Input

To parse true or false text:

System.out.print(
        "Is enrollment open? "
);

boolean enrollmentOpen =
        Boolean.parseBoolean(
                scanner
                        .nextLine()
                        .strip()
        );

Input:

true

Result:

true

However:

yes

is not considered true by Boolean.parseBoolean().

If you want user-friendly yes/no input, you can compare the String:

String answer =
        scanner
                .nextLine()
                .strip();

boolean confirmed =
        answer.equalsIgnoreCase("yes")
        || answer.equalsIgnoreCase("y");

Reading Multiple Inputs

import java.util.Scanner;

public class Main {

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

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

        String name =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter your age: "
        );

        int age =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.println();
        System.out.println(
                "Name: " + name
        );

        System.out.println(
                "Age: " + age
        );

        scanner.close();
    }
}

Possible interaction:

Enter your name: Sakib
Enter your age: 20

Name: Sakib
Age: 20

Why Are We Using nextLine() More Often?

Scanner also provides methods for directly reading typed input:

nextInt()
nextDouble()
nextBoolean()

Example:

int age =
        scanner.nextInt();

These are valid.

However, mixing token-based methods with nextLine() can cause a common newline problem.

For beginners, reading all input using nextLine() and parsing it afterward keeps the input flow more consistent.

The nextInt() and nextLine() Problem

Look at this code:

System.out.print(
        "Enter your age: "
);

int age =
        scanner.nextInt();

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

String name =
        scanner.nextLine();

After the user enters their age and presses Enter, the name input may appear to be skipped.

Why Does the Input Get Skipped?

User input:

20\n

nextInt() reads:

20

but the newline produced by Enter:

\n

can remain in the input stream.

The next call:

scanner.nextLine();

may consume that remaining newline and return an empty String.

Fixing the Problem

One option:

int age =
        scanner.nextInt();

scanner.nextLine();

String name =
        scanner.nextLine();

The extra nextLine() consumes the leftover newline.

However, for beginner code, a more consistent approach is:

int age =
        Integer.parseInt(
                scanner
                        .nextLine()
                        .strip()
        );

In other words, read every input as a full line.

Recommended Input Pattern

For simple console programs in this course, we will generally use this pattern:

String input =
        scanner
                .nextLine()
                .strip();

For text, use it directly:

String name = input;

For an integer:

int age =
        Integer.parseInt(input);

For a decimal:

double price =
        Double.parseDouble(input);

This approach:

  • Consumes the full line
  • Allows whitespace normalization
  • Keeps the input style consistent
  • Reduces nextInt() / nextLine() problems

Invalid Numeric Input

Suppose:

int age =
        Integer.parseInt(
                scanner.nextLine()
        );

The user enters:

twenty

This is not valid integer text.

At runtime, a:

NumberFormatException

can occur.

Type Validity and Business Validity

An input is not necessarily valid just because it is a valid integer.

Example:

Age: -50

-50 is a valid integer.

But it is not valid as an age.

Suppose acceptable age is:

0 to 150

Check:

boolean validAge =
        age >= 0
        && age <= 150;

Therefore, there can be two types of validation:

  1. Whether the input is of the expected type
  2. Whether the value is acceptable according to business rules

Blank Input

String name =
        scanner
                .nextLine()
                .strip();

boolean missing =
        name.isBlank();

Input:

   

Result:

true

isBlank() is useful for checking required text input.

Closing the Scanner

After you finish reading input:

scanner.close();

Example:

Scanner scanner =
        new Scanner(System.in);

// Read all input

scanner.close();

After a Scanner is closed, it cannot be used to read input again.

Therefore, close it only after all input operations are complete.

Reuse One Scanner

Avoid:

Scanner nameScanner =
        new Scanner(System.in);

Scanner ageScanner =
        new Scanner(System.in);

For the same System.in stream, generally create one Scanner and reuse it:

Scanner scanner =
        new Scanner(System.in);

Complete Interactive Program

Now let's create a simple student result program.

import java.util.Scanner;

public class Main {

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

        System.out.print(
                "Enter student name: "
        );

        String studentName =
                scanner
                        .nextLine()
                        .strip();

        System.out.print(
                "Enter mathematics mark: "
        );

        int mathematicsMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter English mark: "
        );

        int englishMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        System.out.print(
                "Enter science mark: "
        );

        int scienceMark =
                Integer.parseInt(
                        scanner
                                .nextLine()
                                .strip()
                );

        int totalMarks =
                mathematicsMark
                + englishMark
                + scienceMark;

        double averageMark =
                totalMarks / 3.0;

        System.out.println();
        System.out.println(
                "Student: " + studentName
        );

        System.out.println(
                "Total: " + totalMarks
        );

        System.out.println(
                "Average: " + averageMark
        );

        scanner.close();
    }
}

Possible interaction:

Enter student name: Sakib
Enter mathematics mark: 80
Enter English mark: 90
Enter science mark: 85

Student: Sakib
Total: 255
Average: 85.0

Common Errors

Not Importing Scanner

Wrong:

Scanner scanner =
        new Scanner(System.in);

If there is no import, the compiler will not recognize Scanner.

Add:

import java.util.Scanner;

Omitting new

Wrong:

Scanner scanner =
        Scanner(System.in);

Correct:

Scanner scanner =
        new Scanner(System.in);

Wrong Input Source

Wrong:

Scanner scanner =
        new Scanner(System.out);

For keyboard input:

Scanner scanner =
        new Scanner(System.in);

Using next() for a Full Name

String name =
        scanner.next();

Input:

Md Sakib

Only:

Md

will be read.

For a full line:

scanner.nextLine();

Parsing an Invalid Number

Wrong input:

twenty

Code:

Integer.parseInt("twenty");

This causes a runtime error.

The input to a numeric parser must use a valid numeric format.

Not Normalizing Input

Input:

   Sakib

Use:

String name =
        scanner
                .nextLine()
                .strip();

Closing the Scanner Too Early

Wrong:

Scanner scanner =
        new Scanner(System.in);

scanner.close();

String name =
        scanner.nextLine();

Close it after all input has been read.

Important Terms

User Input

Data provided by the user while the program is running.

System.in

Java's standard input stream.

Scanner

A Java utility class that helps read input.

Prompt

A message that tells the user what input is expected.

nextLine()

Reads an entire line of input.

Parsing

Interpreting text and creating a value of another type.

Validation

Checking whether input is acceptable.

Normalization

Bringing input into a consistent form.

Examples:

Remove whitespace
Normalize case

NumberFormatException

A runtime exception that can occur when invalid numeric text is parsed.

Practice Exercise 1: Name Input

Read the user's full name.

Input:

Md Samiul Alim Sakib

Output:

Welcome, Md Samiul Alim Sakib

Practice Exercise 2: Age Input

Read the user's age.

Expected interaction:

Enter your age: 20
Next year you will be 21

Practice Exercise 3: Numeric Parsing

Read all input using nextLine():

  • Name
  • Age
  • Course price

Convert:

  • Age → int
  • Price → double

Practice Exercise 4: Normalize Input

Input:

   JAVA

Produce:

java

Use:

  • nextLine()
  • strip()
  • toLowerCase()

Practice Exercise 5: Yes or No

Prompt:

Do you want to continue? Enter yes or no:

Accept the following as positive values:

yes
y
YES
Y

Create a boolean shouldContinue.

Practice Exercise 6: Product Order

Read:

  • Product name
  • Unit price
  • Quantity

Calculate:

subtotal = unit price × quantity

Then print the product information and subtotal.

Practice Exercise 7: Student Result

Read from the user:

  • Student name
  • Mathematics mark
  • English mark
  • Science mark

Calculate:

  • Total
  • Decimal average

Knowledge Check

Question 1

What is the standard stream for keyboard input?

Question 2

Which package contains Scanner?

Question 3

What is the import statement for Scanner?

Question 4

How do you create a Scanner for keyboard input?

Question 5

Which method reads a full line?

Question 6

What can be used to remove surrounding whitespace from input?

Question 7

Which method converts String input to an int?

Question 8

Which method converts String input to a double?

Question 9

Why can nextLine() appear to be skipped after nextInt()?

Question 10

What is the recommended input strategy for beginner console programs in this course?

Question 11

What can happen when invalid numeric text is parsed?

Question 12

Is type-valid input always business-valid?

Question 13

When should a Scanner be closed?

Question 14

Should multiple Scanner instances generally be created for the same System.in?

Knowledge Check Answers

Answer 1

System.in

Answer 2

java.util

Answer 3

import java.util.Scanner;

Answer 4

Scanner scanner =
        new Scanner(System.in);

Answer 5

nextLine()

Answer 6

strip()

Answer 7

Integer.parseInt()

Answer 8

Double.parseDouble()

Answer 9

nextInt() reads the numeric token but can leave the newline from pressing Enter in the input stream. The next nextLine() may consume that newline and return an empty String.

Answer 10

Read all input using nextLine(), normalize it with .strip() when needed, and convert numeric values using parsing methods.

Answer 11

A NumberFormatException can occur.

Answer 12

No. For example, 500 is a valid integer but may be invalid as an age or exam mark.

Answer 13

After all input operations are complete.

Answer 14

Generally, no. It is better to create one Scanner and reuse it.

Lesson Summary

In this lesson, we learned:

  • User input makes a program interactive
  • System.in is the standard keyboard input stream
  • Scanner helps read console input
  • java.util.Scanner must be imported to use Scanner
  • A Scanner can be created using new Scanner(System.in)
  • A prompt helps the user understand the expected input
  • nextLine() reads an entire line
  • .strip() helps normalize input
  • Numeric input can be read as text and then parsed
  • Integer.parseInt() converts String input to int
  • Double.parseDouble() converts String input to double
  • Mixing nextInt() and nextLine() can create a leftover-newline problem
  • Reading all input with nextLine() is a consistent strategy for beginners
  • Parsing invalid numeric text can cause a runtime error
  • Type validation and business validation are different
  • Reusing one Scanner for the same System.in is preferable
  • The Scanner should be closed after all input is complete