In this tutorial, we will learn how to accept input in Java. Java has many different ways to accept user input. Here, we will learn to accept user input using the Scanner class in detail with the example.
User Input Using Scanner
A Scanner is a predefined class in Java and found in java.util package (Library), we need to import before using it. Scanner class has many different methods to access different types of data. Let’s start with the example.
//importing package for Scanner class
import java.util.Scanner;
class Example
{
public static void main(String arg[])
{
//create an object of Scanner
Scanner in=new Scanner(System.in);
String name;
System.out.print("Enter Your Name :");
name = in.nextLine(); //accepting user input
System.out.println("Hello : "+name);
}
}
Enter Your Name : James Gosling
Hello : James Gosling
In the above example, the nextLine() method of Scanner class is used to accept string (text) input and store it in a variable.
Methods of Scanner to Read Input
In Java, Scanner class has many different methods to accept different types of input from the user.
Method | Description | |
---|---|---|
next() | – | To read a word. |
nextLine() | – | To read complete sentence. |
nextBoolean() | – | To read boolean values. |
nextByte() | – | To read, byte. |
nextShort() | – | To read short number. |
nextInt() | – | To read integer values. |
nextLong() | – | To read long numbers. |
nextFloat() | – | To read floating values. |
nextDouble() | – | To read double type. |
Example: Different types of input in Java.
//example to accept different types of values
import java.util.Scanner;
class Example
{
public static void main(String arg[])
{
String pid;
int qty;
double price;
//create an object of Scanner
Scanner in=new Scanner(System.in);
//accepting single word
System.out.print("Enter Product's Id : ");
pid = in.next();
//accepting integer
System.out.print("Enter Product's Quantity : ");
qty = in.nextInt();
//accepting double type
System.out.print("Enter Product's Price : ");
price = in.nextDouble();
System.out.println("Product id is "+pid+" and Price is "+price);
System.out.println("You have ordered Total "+qty+" items");
}
}
Enter Product’s Id : P1001
Enter Product’s Quantity : 5
Enter Product’s Price : 260.55
Product id is P1001 and Price is 260.55
You have ordered Total 5 items
If we enter wrong type of value as input in Java, then it will raise an exception. We must enter right types of values as input.