How to Read Integer From Console in Java

Java provides all the tools needed to read and write from an ordinary text console, and even to parse the information from the console into any of its primitive data types. But actually finding the correct tool amidst the hundreds in the Java library can be a challenge in itself.

Instructions

    • 1

      Open your Java Integrated Development Environment (IDE).

    • 2

      Type the following into a Java file:

      System.out.println("Please enter an integer:");

    • 3

      Type the following on the next line:

      Scanner in = new Scanner(System.in);

      Normally, if you simply wanted to read ordinary text data from the console, you would read it from "System.in" directly, but here you are using "System.in" to create a Scanner object that allows you to collect data from the console in any of a multitude of formats.

    • 4

      Type the following on the next line to actually read the integer from the user:

      int i = in.nextInt();

Tips & Warnings

  • The Scanner class is a powerful tool for taking input from the user, and it can do a lot more than simply read integers from the console. Take a look at the full list of functions for the Scanner class at Oracle's JavaDoc for it.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured