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 |
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