Try Out New Website HTML Table Generator

How we can accept input from the user using Scanner in Java

User input in Java In this article, we will discuss in detail how we can accept input from the user using Scanner in Java. The Scanner class is in...

User input in Java

In this article, we will discuss in detail how we can accept input from the user using Scanner in Java. The Scanner class is in the Java Utility package, and we need to import it before we can use the Scanner.

How to accept user input in Java
How to accept user input in Java

Import scanner!

First, we need to import the Scanner class. Here we write:


import java.util.Scanner;
 

Next, we can create the scanner object:


Scanner scanner = new Scanner(System.in);
 

Approval from user

We can create a prompt for approval from the user and use the scanner:


System.out.println(\"What is your name?\");

String name = scanner.nextLine();

System.out.println(\"Hello\" + name);
 

This way, we can get the name from the user and show the welcome message.

Complete Code

Here we can ask questions related to name, age and favorite food:

System.out.println(\"What is your name?\");

String name = scanner.nextLine();

System.out.println(\"How old are you?\");

int age = scanner.nextInt();

System.out.println(\"What is your favorite food?\");

scanner.nextLine(); // clear the scanner with

String food = scanner.nextLine();

System.out.println(\"Hello \" + name + \", you are \" + age + \" years old and your favorite food is \" + food + \".");
 

Thus, we can make various types of approvals from the user using the scanner.

Subcontact

In this article we saw how scanners can be used in Java and how to accept input from the user. We will learn this in more detail in the upcoming video. If you enjoyed this article, please comment below, and follow us. Thank you!

For More Details: https://en.wikipedia.org/wiki/JavaScript

Rate this article

Loading...

Post a Comment

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing Lantro UI, you agreed to use cookies in agreement with the Lantro UI's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.