Hey guys in this, we will discuss accepting the user input in Java with Scanner class. If we are creating a console-based application, it’s essential that takes the user input and produces the correct output. So in this post let’s see how we can take the user input using the Scanner class.
Table of Contents
Overview
The Scanner class is used to get the user input, and it is found in java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class. There are several methods available in Scanner class for reading different data types.
Methods to read different datatypes
nextBoolean(): As the name suggests, it is used to read thebooleanvalue from the usernextByte(): As the name suggests, it is used to read thebytevalue from the usernextDouble(): As the name suggests, it is used to read thedoublevalue from the usernextFloat(): As the name suggests, it used to read thefloatvalue from the usernextInt(): As the name suggests, it used to read theintvalue from the usernextLine(): As the name suggests, it is used to read theStringvalue from the user.nextLong(): As the name suggests, it is used to read thelongvalue from the user.nextShort(): As the name suggests, it is used to read theshortvalue from the user.
Of course, we cannot discuss all of the methods in detail because that will take a lot of time. Let’s look at the example for taking user input for String, int, and double.
Usage of nextLine()
As we discussed nextLine() is used to read the String value from the user
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
System.out.println("My name is "+name+".");
}
}
Output:
Enter your name:
Bushan Sirgur
My name is Bushan Sirgur.
Usage of nextInt() and nextDouble()
As we discussed nextInt() and nextDouble() is used to read the integer and double value respectively.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
System.out.println("Enter your age:");
int age = scanner.nextInt();
System.out.println("Enter your salary:");
double salary = scanner.nextDouble();
System.out.println("My name is "+name+". I am "+age+" years old. I am earning "+salary+"/-");
}
}
Output:
Enter your name:
Bushan
Enter your age:
28
Enter your salary:
10000
My name is Bushan. I am 28 years old. I am earning 10000.0/-
