![]() |
VOOZH | about |
Scanner is a predefined class in Java used to take input from the user. It is present in the java.util package and supports different types of input such as integers, strings, float values, and characters. The Scanner class makes input handling simple and user-friendly in Java programs.
Example: Java program to demonstrate the use of Scanner class to take input from user
Output:
Explanation: In the above code example, we use the nextLine() of Scanner class to read the line value which is entered by the user and print it in the console.
Import the java.util.Scanner package at the beginning of the program.
import java.util.Scanner
public class Geeks{
public static void main(String [] args){
}
}
Scanner sc = new Scanner (System.in);
Here "sc" is an object of the Scanner class. We can give it different names for our ease such as in, var or obj etc. Using this object we can use the methods of the Scanner class.
int age = sc.nextInt();
The scanner class helps take the standard input stream in Java. So, we need some methods to extract data from the stream. The methods used for extracting data are mentioned below:
Method | Description |
|---|---|
| Used for reading Boolean value | |
| Used for reading Byte value | |
| Used for reading Double value | |
| Used for reading Float value | |
| Used for reading Int value | |
| Used for reading Line value | |
| Used for reading Long value | |
| Used for reading Short value |
Let us look at the code snippet to read data of various data types.
Example 1: Java program to read data of various types using Scanner class
Output:
Explanation: In the above code example, we use the Scanner class to take different types of input values from user and print it in the console.
Example 2: Java program to read some values using Scanner class and print their mean.
Output:
Explanation: In the above code example, we use the hasNext() and hasNextInt() method to take the input values from user and then user give the input value they can specify that the input value is ended and they can type "done" to find the mean value of given input.