User Input

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial tries to take information from the user using the Scanner class. There were several types of datatype as we have seen previously.

Sometimes, we can face a situation where we need to get information from the user at runtime. We use the “Scanner” class to accept user input to obtain user information. The Java Scanner class comes under java.util.package. To use the Scanner class, we need to import the java.util.package to our program.

The syntax for each of the data types is discussed here. Therefore, the user may receive input from the user.

One of the strengths of Java is the huge code libraries available to you. This is the code that has been written to do specific jobs. All you need to do is to reference the library you want to use and then put a method in action.

A really useful class that handles a user’s input is called the Scanner class. The Scanner class is present in the java.util package. To use the scanner class, you need to import this package in our program.

The next thing to do is create an object of the Scanner class. Instead of configuring an int variable or a String variable, we are configuring a Scanner variable. We have called our user input. We have the new keyword after an equal sign to create new objects of a class. The object we are creating is of the Scanner class. In parentheses, you have to tell java that this will be the system’s entry (System.in).

To obtain user input, you can activate one of the many methods available for your new Scanner object. One of these methods is called below. It gets the next string of text that a user types on the keyboard. nextInt( ) method is used to scans the next token of the input as an Int.

So, after our user_input object, we write a dot(.). Next, you will see a pop-up list of available methods. Double-click on Next and type a semicolon to end of the line. We can also print text to notify the user.

Output

What’s your age?

21   //(input by user)

Your age is 21

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu