Scanner nextInt() Method in Java

Taking integer input (nextInt method)

Here is a simple program, in which we are taking the input from the user. In this program, we are going to take an integer number as our input. Have a look at this program. You can easily understand this program. Also, remember that we are taking user input, so we have to store it somewhere, which is why we also created a variable so that we can store the user input value.

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Please enter a number: “);
int var = scanner.nextInt();
System.out.println(“You entered: “+var);
}
}

so, as an output of the above program, we get whatever integer value we have entered.

Output →

Please enter a number: 23

You entered: 23

You can also try the same program on your computer. If your program throws some error, it might be due to the package name. So, I suggest you create your own project in IntelliJ idea first (or whatever IDE you are using), and then write this code. Or you can also write it in some text editor like notepad, and compile and execute it with help of a terminal (You can search how to do this, anyways we are going to take this concept a little bit later but you can refer to it now also. You can find the topic under the name How to compile and execute java programs without using IDE).

So, observe that we have taken an integer input from the user. For doing this, we have made the use of a method called as nextInt() which is present inside the class Scanner. This is why we create the object of the Scanner class so that we can use these methods. By the way, the System.in which is written while we create the object of the Scanner class, tells us that we are going to take the input from the keyboard.

Well, in this program, we have made use of the nextInt() method, with which we can take the int type user input.