Take input from he user

description of image


Java Scanner


We use the Scanner class to take input from users.

To use Scanner, we must add the line


Import java.util.Scanner;


At the beginning of our program.


This imports the Scanner class Inside Our program.


Create Scanner Object:

Once the Scanner class is imported, we need to create an object from it.


Scanner input = new Scanner (System.in);

Here, input is an object of Scanner which will be used to take input. The System. In specifies we will take input from the standard input (keyboard).


Note: We will learn about objects and classes in detail in the upcoming lessons.



Take int input


● We use the nextInt() method of the Scanner class to take an integer input from the user.

Notice the line

Int data = input.nextInt();

● It takes integer input from the user and stores it to the data variable.

And, the line

Input.close();

Closes Scanner. It’s a good practice to close Scanner after it is used.



Quiz


Question Text