You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Answer from polygenelubricants on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-read-and-print-an-integer-value-in-java
How to Read and Print an Integer Value in Java - GeeksforGeeks
May 12, 2026 - It explains different methods like Scanner and BufferedReader to take integer input from the user and display it on the screen. The Scanner class in java.util package is the easiest way to take input from the user in Java. It reads data from various input sources, including the keyboard.
Discussions

[Java] What is the best way to read a user defined integer value?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
6
3
August 22, 2023
My Java code will not wait for user input when I ask the user for a new input

See The Scanner class and its caveats from our wiki.

It explains your problem and the solution to it.

More on reddit.com
๐ŸŒ r/javahelp
6
1
October 14, 2018
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2017 โ€บ 09 โ€บ java-program-to-read-integer-value-from-the-standard-input
Java Program to read integer value from the Standard Input
October 25, 2022 - import java.util.Scanner; public ... Scanner(System.in); System.out.print("Enter any number: "); // This method reads the number provided using keyboard int num = scan.nextInt(); // Closing Scanner after the use scan.close(); // Displaying the number System.out.println("The number entered ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ read-integers-from-console-in-java
Read integers from console in Java
To read integers from console, use Scanner class. ... Allow a use to add an integer using the nextInt() method. System.out.print( "Enter first integer: " ); int a = myInput.nextInt(); In the same way, take another input in a new variable.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-read-a-long-integer-input-using-scanner-in-java-417653
How to read a long integer input using Scanner in Java | LabEx
The Scanner class is part of the ... class to read different types of input. For example, to read an integer, you can use the nextInt() method:...
๐ŸŒ
TutorialKart
tutorialkart.com โ€บ java โ€บ java-read-integer-from-console
Java - Read Integer from Console
May 4, 2023 - In Java, you can read integer from Console using nextInt() on Scanner. First of all, to read anything from the console, you have to create a Scanner with System standard input of the computer.
๐ŸŒ
Code2care
code2care.org โ€บ home โ€บ java programs โ€บ how to read int value using scanner class java
How to read int value using Scanner Class Java | Code2care
January 26, 2026 - package org.code2care.java.examples; ... scanner = new Scanner(System.in); System.out.print("Enter an int value: "); int inputtedIntValue = scanner.nextInt(); System.out.println("Entered int value: " + inputtedIntValue); ...
Find elsewhere
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-read-integer-input-correctly-502975
How to read integer input correctly | LabEx
import java.util.Scanner; public ... for input System.out.print("Enter an integer: "); // Read the integer input int userInput = scanner.nextInt(); // Close the scanner to prevent resource leak scanner.close(); // Display the ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [java] what is the best way to read a user defined integer value?
r/learnprogramming on Reddit: [Java] What is the best way to read a user defined integer value?
August 22, 2023 -

I'm brushing up on my Java programming by going through the free Java course through the University of Finland. In the course, they teach that the only way to read a user define integer is to do the following:

int value = Integer.valueOf(scanner.nextLine());

But, back when I was in college, we were taught that using the following was okay as well:

int value = scanner.nextInt();

Which one is actually correct or are they both right?

๐ŸŒ
DEV Community
dev.to โ€บ sbu_05 โ€บ reading-an-string-after-an-integer-4jbp
Reading a String after an Integer - DEV Community
March 12, 2021 - When receiving input, in most ... Scanner class allows us to read in input as Double Integer or a Float using the methods nextInt() and nextDouble()....
๐ŸŒ
Java2Blog
java2blog.com โ€บ take-integer-input-java
How to Take Integer Input in Java โ€“ Java2Blog
September 16, 2022 - We need to import java.util.Scanner class to use Scanner. To read integer input from the user first need to create an object of Scanner class by passing System.in.
๐ŸŒ
Codefinity
codefinity.com โ€บ courses โ€บ v2 โ€บ 8bdbdd9f-a2a1-4a34-a8f4-240fb6f735eb โ€บ 8a536240-0589-431b-9bee-da9ed965ea01 โ€บ a885733b-0575-41cc-9ce3-b3aa4ceefa31
Learn Reading Integers from User Input | Handling Different Types of Input
When you want to read an integer from the user in Java, you use the nextInt() method from the Scanner class. This method reads the next input token as an integer, allowing you to easily prompt the user for numbers such as age, quantity, or any ...
๐ŸŒ
Java Code Geeks
javacodegeeks.com โ€บ home โ€บ core java
Java Input Handling: Read Multiple Integers from One Line - Java Code Geeks
November 25, 2024 - It can be used to read multiple integers from a single line of input, either by repeatedly reading integers until the input ends or by reading the entire line and parsing it. Below are two approaches to solving this problem using Scanner.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ take-an-integer-input-java
Taking Integer Input in Java: A Comprehensive Guide โ€” javaspring.net
We then use the nextInt() method to read an integer from the user. Finally, we print the entered integer and close the scanner to release resources. The BufferedReader class is another way to take input from the user in Java.
Top answer
1 of 4
6

java.util.Scanner is the best choice for this task.

From the documentation:

For example, this code allows a user to read a number from System.in:

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

Two lines are all that you need to read an int. Do not underestimate how powerful Scanner is, though. For example, the following code will keep prompting for a number until one is given:

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
while (!sc.hasNextInt()) {
    System.out.println("A number, please?");
    sc.next(); // discard next token, which isn't a valid int
}
int num = sc.nextInt();
System.out.println("Thank you! I received " + num);

That's all you have to write, and thanks to hasNextInt() you won't have to worry about any Integer.parseInt and NumberFormatException at all.

See also

  • Java Tutorials/Essential Classes/Basic I/O/Scanning and Formatting

Related questions

  • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
  • How to use Scanner to accept only valid int as input

Other examples

A Scanner can use as its source, among other things, a java.io.File, or a plain String.

Here's an example of using Scanner to tokenize a String and parse into numbers all at once:

Scanner sc = new Scanner("1,2,3,4").useDelimiter(",");
int sum = 0;
while (sc.hasNextInt()) {
    sum += sc.nextInt();
}
System.out.println("Sum is " + sum); // prints "Sum is 10"

Here's a slightly more advanced use, using regular expressions:

Scanner sc = new Scanner("OhMyGoodnessHowAreYou?").useDelimiter("(?=[A-Z])");
while (sc.hasNext()) {
    System.out.println(sc.next());
} // prints "Oh", "My", "Goodness", "How", "Are", "You?"

As you can see, Scanner is quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.

See also

  • Java Tutorials/Essential Classes/Regular expressions
  • regular-expressions.info/Tutorial

Related questions

  • Scanner vs. StringTokenizer vs. String.Split
2 of 4
5

Here's my entry, complete with fairly robust error handling and resource management:

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

/**
 * Simple demonstration of a reader
 *
 * @author jasonmp85
 *
 */
public class ReaderClass {

    /**
     * Reads two integers from standard in and prints their sum
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        // System.in is standard in. It's an InputStream, which means
        // the methods on it all deal with reading bytes. We want
        // to read characters, so we'll wrap it in an
        // InputStreamReader, which can read characters into a buffer
        InputStreamReader isReader = new InputStreamReader(System.in);

        // but even that's not good enough. BufferedReader will
        // buffer the input so we can read line-by-line, freeing
        // us from manually getting each character and having
        // to deal with things like backspace, etc.
        // It wraps our InputStreamReader
        BufferedReader reader = new BufferedReader(isReader);
        try {
            System.out.println("Please enter a number:");
            int firstInt = readInt(reader);

            System.out.println("Please enter a second number:");
            int secondInt = readInt(reader);

            // printf uses a format string to print values
            System.out.printf("%d + %d = %d",
                              firstInt, secondInt, firstInt + secondInt);
        } catch (IOException ioe) {
            // IOException is thrown if a reader error occurs
            System.err.println("An error occurred reading from the reader, "
                               + ioe);

            // exit with a non-zero status to signal failure
            System.exit(-1);
        } finally {
            try {
                // the finally block gives us a place to ensure that
                // we clean up all our resources, namely our reader
                reader.close();
            } catch (IOException ioe) {
                // but even that might throw an error
                System.err.println("An error occurred closing the reader, "
                                   + ioe);
                System.exit(-1);
            }
        }

    }

    private static int readInt(BufferedReader reader) throws IOException {
        while (true) {
            try {
                // Integer.parseInt turns a string into an int
                return Integer.parseInt(reader.readLine());
            } catch (NumberFormatException nfe) {
                // but it throws an exception if the String doesn't look
                // like any integer it recognizes
                System.out.println("That's not a number! Try again.");
            }
        }
    }
}
๐ŸŒ
YouTube
youtube.com โ€บ math and science
Java Tutorial - 03 - Read Integers and Doubles from Keyboard with Scanner - YouTube
Get more lessons like this at http://www.MathTutorDVD.com Learn how to read more types of data from the keyboard such as floating point decimals, doubles, an...
Published: March 25, 2018
Views: 7K
๐ŸŒ
Just Academy
justacademy.co โ€บ blog-detail โ€บ how-to-take-integer-input-in-java
How to Take Integer Input in Java by Roshan Chaturvedi | JustAcademy
2) First, create a `Scanner` object by importing the `Scanner` class and instantiating it as follows: ... 3) To read an integer input from the user, you can use the `nextInt()` method of the `Scanner` class.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Learn Java Tutorial #10 - Scanner Read Int and Double - YouTube
****** Click here to subscribe: https://goo.gl/G4Ppnf ******Hi guys! Welcome to Java Tutorial, in this video we'll talk about how to read data from the k...
Published: November 13, 2019
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ java-program-to-read-integer-value-from-the-standard-input
Java Program to Read Integer Value from the Standard Input
December 20, 2024 - package RemainingSimplePrograms; ... = new Scanner(System.in); System.out.print("Enter Any Integer Value = "); int num = sc.nextInt(); sc.close(); System.out.println("Given Integer Value = " + num); } }...