You can get integer input in Java using the Scanner
class. Here's how:
-
Import the Scanner class:
import java.util.Scanner;
-
Create a Scanner object:
Scanner scanner = new Scanner(System.in);
-
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 callingnextInt()
. 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 theInteger.parseInt()
method. This is useful if you need to handle multiple inputs on a single line.