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
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 forms the base for performing calculations, conditions, and logical operations in Java programs ยท It explains different methods like Scanner and BufferedReader to take integer input from the user and display it on the screen.
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.");
            }
        }
    }
}
๐ŸŒ
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 class Demo { public static void main(String[] args) { /* This reads the input provided by user * using keyboard */ Scanner scan = new 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 by user: "+num); } }
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ print an integer (entered by the user)
Java Program to Print an Integer (Entered by the User) | Vultr Docs
September 27, 2024 - Explore different examples illustrating how to implement this simple but essential task using various Java methods. Import the Scanner class which is used to read data entered by the user. Create an instance of 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.
๐ŸŒ
UW Computer Sciences
pages.cs.wisc.edu โ€บ ~hasti โ€บ cs368 โ€บ JavaTutorial โ€บ NOTES โ€บ JavaIO_Scanner.html
Java Input and Output (I/O)
September 3, 2008 - Use the Integer class to parse the string of characters into an integer. int number = Integer.parseInt( input ); // converts a String into an int value The Integer class contains conversion methods for changing String data into int values and vice versa. The Integer class is one of several ...
๐ŸŒ
Java2Blog
java2blog.com โ€บ take-integer-input-java
How to Take Integer Input in Java โ€“ Java2Blog
September 16, 2022 - We can take input as an integer from a user, with the help of the Scanner class. In java.util package Scanner class is present.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ read-integers-from-console-in-java
Read integers from console in Java
In the same way, take another input in a new variable. System.out.print( "Enter second integer: " ); Int b = myInput.nextInt(); Let us see the complete example. import java.util.Scanner; public class Demo { public static void main( String args[] ) { Scanner myInput = new Scanner( System.in ); int a; int b; int sum; System.out.print( "Enter first integer: " ); a = myInput.nextInt(); System.out.print( "Enter second integer: " ); b = myInput.nextInt(); sum = a + b; System.out.printf( "Sum = %d\n", sum ); } }
๐ŸŒ
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 ... data type of interest. In Java, the Scanner class allows us to read in input as Double Integer or a Float using the methods nextInt() and nextDouble()....
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_user_input.asp
Java User Input (Scanner class)
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... The Scanner class is used to get user input, and it is found in the java.util package.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ print-integer
Java Program to Print an Integer (Entered by the User) | Programiz
March 21, 2024 - The integer is stored in a variable using System.in, and is displayed on the screen using System.out. To understand this example, you should have the knowledge of the following Java programming topics: ... import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { // Creates a reader instance which takes // input from standard input - keyboard Scanner reader = new Scanner(System.in); System.out.print("Enter a number: "); // nextInt() reads the next integer from the keyboard int number = reader.nextInt(); // println() prints the following line to the output screen System.out.println("You entered: " + number); } }
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ how to get user input in java
Java Get User Input from Console | Sentry
September 3, 2026 - For example, the following code uses Scanner with methods such as nextLine() to retrieve different data 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(); // Read a full line of text System.out.println("Hello, " + name + "!"); System.out.print("Enter your age: "); int age = scanner.nextInt(); // Read an integer input System.out.println("You are " + age + " years old."); System.out.print("Enter a decimal number: "); double number = scanner.nextDouble(); // Read a double input System.out.println("You entered: " + number); scanner.close(); // Close the scanner to free resources } } This demonstrates the following commonly used methods for reading user input: The nextLine() method reads a full line of text.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-check-if-input-is-integer-117391
Check if Input Is Integer in Java | LabEx
We can use this behavior to validate integers. Add the following method to your CheckInputInteger.java file: // Add this method inside the CheckInputInteger class public static void checkUsingParseInt(String input) { try { // Attempt to parse the input string to an integer Integer.parseInt(input); System.out.println(input + " is a valid integer"); } catch (NumberFormatException e) { // If parsing fails, the input is not a valid integer System.out.println(input + " is not a valid integer"); } }
๐ŸŒ
Just Academy
justacademy.co โ€บ blog-detail โ€บ how-to-take-integer-input-in-java
How to Take Integer Input in Java by Roshan Chaturvedi | JustAcademy
In Java, taking integer input is a common practice when developing programs that require numerical values from the user. This input is typically done using classes like Scanner or BufferedReader, which allow for user input to be read and stored ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java Program to Get User Input and Print an Integer - YouTube
Learn how to take an integer input from a user in Java and print it to the console screen. In this beginner-friendly Java programming tutorial, we build a cl...
Published: March 7, 2020
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ Java-program-to-accept-an-integer-from-user-and-print-it
Java program to accept an integer from user and print it
October 18, 2024 - Import the Scanner class from the java.util package to handle user input. Create an instance of the Scanner class to read the input from the user and ask the user to enter an integer.
๐ŸŒ
Medium
w3developers.medium.com โ€บ java-program-to-print-an-integer-entered-by-the-user-0bab9fb7e1cc
Java Program to Print an Integer (Entered by the User) | by Mouad Oumous | Medium
September 5, 2024 - User input in Java can be handled using various classes, but one of the most common and straightforward ways is through the Scanner class, which is part of the java.util package. This class provides methods to read different types of input, such as integers, strings, and doubles, from various input sources like the keyboard.