0
0
Javaprogramming~5 mins

Reading integer input in Java

Choose your learning style9 modes available
Introduction

We use reading integer input to get numbers from the user while the program is running. This helps the program work with data the user provides.

When you want the user to enter their age.
When you need a number to calculate something, like adding two numbers.
When you ask the user to choose an option from a menu by typing a number.
When you want to get a score or count from the user.
When you need to read any whole number from the keyboard.
Syntax
Java
import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();

You must import java.util.Scanner to read input.

nextInt() reads the next whole number typed by the user.

Examples
This reads an integer and stores it in the variable age.
Java
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
This asks the user to enter a number and reads it into num.
Java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
Sample Program

This program asks the user to type an integer, reads it, and then prints it back.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int userNumber = scanner.nextInt();
        System.out.println("You entered: " + userNumber);
        scanner.close();
    }
}
OutputSuccess
Important Notes

Always close the Scanner after use with scanner.close() to free resources.

If the user types something that is not an integer, the program will throw an error.

Summary

Use Scanner and nextInt() to read integer input from the user.

Remember to import java.util.Scanner and close the scanner when done.

Reading input lets your program interact with the user by using their numbers.