If you want to read input from the user in a Java Application, you should make use of the Scanner class file from java.util package.
If you specifically want to read an int value, then you can make use of the nextInt() method from the Scanner class.
Program
package org.code2care.java.examples;
import java.util.Scanner;
public class ReadIntegerScannerProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an int value: ");
int inputtedIntValue = scanner.nextInt();
System.out.println("Entered int value: " + inputtedIntValue);
scanner.close();
}
}
Note: You will get an InputMismatchException if the user inputted value is not of type int or Integer.
Enter an int value: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at org.code2care.java.examples.ReadIntegerScannerProgram.main(ReadIntegerScannerProgram.java:12)
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!