The scanner is a class in the java.util package that is used to take input of primitive types such as int, double, etc., and string. This is the easiest way to read input into a Java program, but not very effective when you need input methods for time-limited scenarios such as competitive programming.
Let us look at the code snippet to read data of various data types.
// Java program to read data of various types using Scanner class. import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // String input String name = sc.nextLine(); // Character input char gender = sc.next().charAt(0); // Numerical data input // byte, short and float can be read // using similar-named functions. int age = sc.nextInt(); long mobileNo = sc.nextLong(); double cgpa = sc.nextDouble(); // Print the values to check if the input was correctly obtained. System.out.println("Name: "+name); System.out.println("Gender: "+gender); System.out.println("Age: "+age); System.out.println("Mobile Number: "+mobileNo); System.out.println("CGPA: "+cgpa); } }
Input :
Geek F 40 9876543210 9.9
Output :
Name: Geek Gender: F Age: 40 Mobile Number: 9876543210 CGPA: 9.9
Sometimes we need to check if the next value we read is of a certain type or if the input is complete (EOF tag found).
We then check if the scanner input is the type we want by using the hasNextXYZ() function, where XYZ is the type we are interested in. The function returns true if the scanner has a flag of this type, otherwise false. For example, in the following code, we use hasNextInt(). To search for a string, we use hasNextLine(). Similarly, we use hasNext() to search for characters. CharAt(0).
Let's take a look at the code snippet to read some numbers from the console and print the average.
// Java program to read some values using Scanner // class and print their mean. import java.util.Scanner; public class ScannerDemo2 { public static void main(String[] args) { // Declare an object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Initialize sum and count of input elements int sum = 0, count = 0; // Check if an int value is available while (sc.hasNextInt()) { // Read an int value int num = sc.nextInt(); sum += num; count++; } int mean = sum / count; System.out.println("Mean: " + mean); } }
Input:
101 223 238 892 99 500 728
Output:
Mean: 397
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.