The Scanner class of the “java.util” package is of significant importance as it provides various methods for taking user input. It plays a vital role in creating a bi-directional communication between the user and the application. The Scanner class is ideal for processing, scanning, and parsing the data to different data types such as int, float, long, string, etc.
However, to use the functionality of the Java Scanner class, it is first required to be imported within the code. Multiple different methods for importing the Scanner class in Java are discussed in this article.
How to Import a Scanner Class in Java?
There are two different methods for including the Java Scanner class. The basic syntax for classes from a package in Java is given as follows:
import packagename.classname;
The Scanner class can be imported from the java.util.package using the above-mentioned syntax:
import java.util.Scanner;
Method 1: Using import java.util.Scanner;
The standard practice of importing the Scanner class is by specifying its name using the import statement. The following example demonstrated the inclusion of the Scanner class and using its static method to read user input.
First, the Scanner class is imported from the “util” package for reading a string input. Then, the Scanner object “input” is created that accepts the input via keyboard. The print statement prompts the user to provide a string as input:
Scanner input= new Scanner(System.in);
System.out.println("Enter a string");
The input provided by the user is read by the nextLine() function of the scanner class which is invoked using the scanner object “input”. The user input will be stored in a “str” which is printed via the “System.out.println()”:
String str=input.nextLine();
System.out.println("The string is : " + "\"" + str + "\"");
Complete Code And Output
Method 2: Using import java.util.*
Another method of including the Scanner class in Java is by using the import statement with the asterisk (*) symbol. The asterisk symbol indicates that all the classes and functions of the specified package are included within the code. This approach is also known as the “WildCard Import”.
Within this example, the Scanner class reads the contents of the given file. For this, the necessary classes and static functions are imported from the “java.util” and “java.io” packages:
import java.util.*;
import java.io.*;
Within the try block, an object of File class “file” is created and the file’s path which is to be read is passed to the constructor. The scanner object is passed the file object as an argument within the constructor. The while loop executes if hasNextLine() returns true (meaning that there is data for reading). The nextLine() function of the Scanner class reads the line and stores it in the “string” variable. The output is displayed afterward:
try {
File file = new File("C:\\Users\\Desktop\\textdoc.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
}
The catch block is used for exception handling. In case the user has passed the file’s path that does not exist in the system, an exception is thrown informing the user that the file is not found:
catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
}
Complete Code & Output
This approach will impact the performance of the code. This is because the classes that are not required for the code execution are also imported.
Method 3: Using Scanner Class Object Creation
In Java, developers can also use the Scanner class by directly including it in the main() method without any import statement. The following line of code indicates the inclusion of the Scanner class. The input is a Scanner class object that accepts and reads the input via keyboard:
java.util.Scanner input =new java.util.Scanner(System.in);
In this example, the user is displayed two options i.e., dine-in or takeaway. The user’s input is in the form of alphabets stored in the string “answer” variable. The input object invokes the next() method of the Scanner class that reads the user’s input:
System.out.println("Select any choice");
System.out.println("A : Dine-in");
System.out.println("B: Take away");
String answer=input.next();
The switch statement functions similarly to if-else statement. The case blocks are executed based on the user input as shown in the code below:
switch(answer)
{
case "A":
System.out.println("You selected Option A.");
break;
case "B":
System.out.println("You selected Option B.");
break;
default:
System.out.println("Invalid choice.");}
Complete Code & Output
Performance Analysis: Which one is the Ideal Approach?
To choose which one is the ideal approach, there are different considerations for it i.e., code readability, complexity, compilation, etc. In most cases, the “import java.util.Scanner;” is considered an ideal approach for the following reasons:
Improves Readability: It increases the readability and provides a clear picture of the class that is imported and required in the code.
Enhances Code Performance: Specifying the name of the class in the import statement improves the code performance as it only includes the necessary classes and functions.
Cleaner Code: The “import java.util.Scanner;” provides cleaner code than using the fully qualified name convention.
Scanner VS BufferedReader VS Console
To read input in Java, BufferedReader, and Console classes are also used. However, the three must be used according to the requirement.
Class | Advantage | Disadvantage |
---|---|---|
Scanner | Supports different data types. Easy to Implement | Not suitable for larger streams of data. Not efficient for threads |
BufferedReader | Best suited for the larger inputs. Supports thread functionality. | Imports multiple libraries. Supports String data types |
Console | Simple to Use Best suited for Console-Based Applications | Does not provide versatility as compared to the Scanner and BufferedReader Class. Not compatible with interactive environments. |
Common Exception While Importing the Scanner Class
The exception “Scanner cannot be resolved to a type” may sound confusing for new developers. This exception is often caused when the Scanner class functions are used within the code without referencing the Scanner class:
Shortcut Solution
An easy method for importing the Scanner class within your code is to press “CTRL + Backspace” on the Scanner object to explicitly include the class:
That is all from this guide for importing the Scanner class in Java.
Conclusion
Importing the Scanner class in Java is a common practice for reading the input from various sources. The Scanner class divides the input into tokens and the scanner object reads each token using different methods. To import the Java Scanner class, use “import java.util.Scanner;”, “import java.util.*”, or a Scanner class object creation. The three approaches discussed can be alternatively used depending upon the user requirement.
This guide is a practical walkthrough to import the Scanner class in Java using different methods.