How to read int value using Scanner Class Java


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();
    }
}

Enter an int value: 20
Entered int value: 20


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)

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap