A2oz

How to Get Integer Input in Java?

Published in Programming 2 mins read

You can get integer input in Java using the Scanner class. Here's how:

  1. Import the Scanner class:

    import java.util.Scanner;
  2. Create a Scanner object:

    Scanner scanner = new Scanner(System.in);
  3. Use the nextInt() method to read an integer:

    int number = scanner.nextInt();

Example:

import java.util.Scanner;

public class IntegerInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();
        System.out.println("You entered: " + number);
    }
}

Explanation:

  • The Scanner class allows you to read input from the user.
  • The nextInt() method reads the next integer token from the input stream.
  • The System.out.print() method displays a message to the user prompting them to enter an integer.
  • The System.out.println() method prints the entered integer back to the console.

Practical Insights:

  • You can use the hasNextInt() method to check if the next token in the input stream is an integer before calling nextInt(). This can prevent errors if the user enters non-integer data.
  • You can use the nextLine() method to read an entire line of input and then parse it to an integer using the Integer.parseInt() method. This is useful if you need to handle multiple inputs on a single line.

Related Articles