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
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.");
            }
        }
    }
}
🌐
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 helps in building interactive programs by taking user input at runtime · 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.
🌐
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 - This value is taken from the user with the help of nextInt() method of Scanner Class. The nextInt() method, in Java, reads the next integer value from the console into the specified variable.
🌐
Just Academy
justacademy.co › blog-detail › how-to-take-integer-input-in-java
How to Take Integer Input in Java by Roshan Chaturvedi | JustAcademy
By incorporating integer input, ... us for more information: +91 99871842961 - Use the `Scanner` class from the `java.util` package to take integer input in Java....
🌐
Java2Blog
java2blog.com › take-integer-input-java
How to Take Integer Input in Java – Java2Blog
September 16, 2022 - In this article, we learned how to declare, initialize and take integers from users with the help of the Scanner class. Using the nextInt() method of the Scanner class we can take input from the console and store the value in the Integer variable. This is all about taking an integer input in Java.
🌐
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 ...
🌐
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.
Find elsewhere
🌐
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: Java Hello World Program · Java Basic Input and Output · 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); } } Output ·
🌐
TutorialsPoint
tutorialspoint.com › read-integers-from-console-in-java
Read integers from console in Java
Java Object Oriented Programming Programming · To read integers from console, use Scanner class. Scanner myInput = new Scanner( System.in ); Allow a use to add an integer using the nextInt() method.
🌐
UW Computer Sciences
pages.cs.wisc.edu › ~hasti › cs368 › JavaTutorial › NOTES › JavaIO_Scanner.html
Java Input and Output (I/O)
September 3, 2008 - In our case, we needed to convert a String object into an int value. The parseInt method of the Integer class performs this action. Be sure to review the Integer class javadoc for more information about this and other methods of the Integer class. ... Read the next available input as an int value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › scanner-class-in-java
Scanner Class in Java - GeeksforGeeks
Scanner is a predefined class in Java used to take input from the user. It is present in the java.util package and supports different types of input such as integers, strings, float values, and characters.
Published: May 27, 2026
🌐
Programiz
programiz.com › java-programming › basic-input-output
Java Basic Input and Output | Programiz
March 21, 2024 - We can use the object to take input from the user. // create an object of Scanner Scanner input = new Scanner(System.in); // take input from the user int number = input.nextInt(); import java.util.Scanner; class Input { public static void ...
🌐
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
🌐
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 ... 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."); ...
🌐
W3Schools
w3schools.com › java › java_user_input.asp
Java User Input (Scanner class)
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like "InputMismatchException"). You can read more about exceptions and how to handle errors in the Exceptions chapter. Tip: For a complete reference of Scanner methods, go to our Java Scanner Reference.
🌐
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.
🌐
LearnYard
read.learnyard.com › java-fundamentals › user-input-in-java
User Input in Java
November 8, 2024 - Take user input - Using the Scanner input object along with the . dot operator and nextInt() method to take integer input, we actively gather the user's input. It's like having a conversation where we ask a question, and the user responds, and ...
🌐
Csias
csias.in › how-do-we-take-the-input-of-a-string-after-taking-an-integer-as-an-input-in-java
How do we take the input of a string after taking an integer as an input in Java?
To take input of a integer we use nextInt() function, that does not read the new line character of your input. So, when we command nextLine() it will take it as new line and give you as a new line.
🌐
TutorialsPoint
tutorialspoint.com › 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.