In Java, we can read the input data from the user with the help of the Scanner
class. The Scanner
class is part of the java.util
package.
This is the syntax of the Scanner
class:
Scanner
class by passing System.in
as a parameter to its constructor.System.in
represents the standard input stream.Scanner object_name = new Scanner(System.in);
We can use the following methods based on the input type:
Input type | Method |
---|---|
String | nextLine() |
Short | next short() |
Int | nextInt() |
Double | nextDouble() |
Byte | nextByte() |
Float | nextFloat() |
Long | nextLong() |
Boolean | nextBoolean() |
BigInteger | nextBigInteger() |
BigDecimal | nextBigDecimal() |
To execute the code given below, enter input in this format with a single whitespace between each input variable:
Name Age GPA
import java.util.Scanner;class Main {public static void main(String[] args){//("Enter name");//("Enter Age");//("Enter GPA");// Creating an object of ScannerScanner obj = new Scanner(System.in);String name = obj.next();int age = obj.nextInt();float gpa = obj.nextFloat();System.out.println("Name="+name);System.out.println("Age="+age);System.out.println("GPA="+gpa);}}
Enter the input below
Scanner
class, that is,
import java.util.Scanner;
.Name
,Age
, and GPA
values.Scanner
class. There is a list of available methods from which we can select a method to use.