How to Close Scanner in JAVA

11 months ago 57

The Scanner class on the Java program can be closed by using the close method. The close method is a public void function that is already implemented in the Java scanner utility class. It closes all the operations on...

How to close the Scanner method in java

The Scanner class on the Java program can be closed by using the close method. The close method is a public void function that is already implemented in the Java scanner utility class. It closes all the operations on the Scanner object when called. The following sections outline how this is done correctly.

Overview of the scanner in Java

The Java scanner is a class in the utility packages of the Java programming language that is imported using the code “import java.util.Scanner”. It acts as a gateway of communication between the user and the software. Precisely, it is a class that allows the user to type in the information that can be used by the software or program to complete the process. The scanner class has several functions that are used in accomplishing different tasks. Some of the functions include the following:

nextInt(); reads data of type integer from the user. nextFloat(): reads data of type float from the user. nextBoolean(): reads the Boolean data type from the user. nextLine(); read a single line from the user. nextByte(): used in reading Bytes from the user. nextLong(): reads the data type long from the user.

The nextLine() function to read data from the user

Figure 1: The nextLine() function to read data from the user.

Figure 1 shows the nextLine() function that is used in reading data from the user.

After using the above functions to read data from the user the function has to be closed to avoid run time errors.

The close() Method Explained

The java. util.Scanner. close() is used in closing the scanner. Closing the class means that all the operations that are involved shall be stopped. When the scanner is not closed then it can easily be invoked by the program thus causing runtime error. The close() function is a void method that does not need any parameters or return value i.e. (public void close()).

The scanner class and the close function

Figure 2: The scanner class and the close function.

The scanner class operates in three processes. The first process is through calling the package using the code Scanner cs=new Scanner(System. in ) on line 39 in Figure 1. The cs is the variable that is given to access its resources easily. The second process is through calling functions that are used in reading data from the user. The function that is called depends on the type of data that is being read from the user. On figure 1 line 46 cs.nextLine() function was called. Meaning that the next line was read by the user. The final stage was the close stage in which the close() function was called to close the operations. An example of the close code is in Figure 1 line 66.

Best Practices for Using Scanner

The scanner is a class that is used in passing different data types to the program. The following are some of the best practices while using it:

Use of the nextLine() function to read a line of text. Use methods like nextInt(), nextLong(),nextFloat() and nextDouble for reading numbers or else the program shall display errors. Using the hasNext() function to check available tokens. Setting the delimiters when using the Scanner class to read data from external files like CSV and text files. Closing the Scanner methods using the close function after the use. Use of try-catch methods while closing the Scanner.

Troubleshooting Common Scanner Issues

Many issues can occur when using the Scanner class. Some of the issues are outlined as follows.

Handling incorrect input values

The most common one is the InpuMismatachException, it mainly occurs when the input that has been provided by the user does not match the expected type. For example when we use the nextInt() method on the code and the user enters the string instead of an integer the inputMistmatchExcetion shall be displayed. The issue can be solved by using a try-catch block. The block shall print an error message and request the user to provide another input.

Handling incorrect input values

Figure 3: Handling incorrect input values

In the attached code when the user provides a string data type instead of an integer data type, the code shall print the value and the message, “Invalid input”. The user shall be able to understand the error and provide another value.

Reading past the end of any Input

NoSuchElementExpection shall be thrown when using methods such as next(), nextInt() and the other functions when no more data is available to be read to the program. To avoid such errors functions such as hasNext(),hasNextLine() and many others have to be used to check if there is another token to be read.

Enhancing the Code Efficiency with the Scanner Closure

If the Scanner is not closed then the program shall not be able to garbage collect the scanner objects and we shall have memory leaks on the program. To avoid memory leaks on the code we should close the Scanner after we have finished reading the inputs from the user or files. The void close() public scanner method allows the Java program to reclaim the scanner memory and use it in other functions. The scanner should always be closed after exhausting inputs from the user or files to avoid memory leaks.

Implementing the close() Method Correctly

The scanner close method should be used within the try-catch block to throw an exception if there is an error. Figure 3 below shows the correct implementation of the scanner close method.

Correct implementation of the close method

Figure 4: Correct implementation of the close method 

Understanding the Impact of Open Scanners

An unclosed Scanner causes a memory leak in the program due to incomplete garbage collection on the Scanner object. The program will mismanage the memory allocation since the memory that is not needed in the Scanner object is not released through closing the Scanner class. Memory leaks cause an increase in memory usage.

Advanced Tips for Scanner Management

The scanner can be managed in the following ways:

Using the try-catch block to throw exception errors when not implemented correctly or when the use provides an invalid input. Use of hasNext(),hasNextInt() and many others to find if the program has reached the end of reading the tokens to avoid runtime errors. Closing the Scanner by using the close method to avoid memory leaks in the program.

Dealing with IllegalStateException

IllegalStateException is a runtime exception that is thrown when a method is called at an incorrect time. To avoid the illegalStateException the program should make sure that the method is not called at an incorrect time. An example of this is when reading data from a file using the Scanner class in a while loop, we should close the Scanner at the end of the while loop. If we close the Scanner within the loop an illegalStateException shall be thrown.

FAQ:

How do you properly close a Scanner in Java?

The scanner can be closed using the close method. The close method is Java in build scanner method that is meant for stopping all the operations that are involved with the Scanner class. The close method should be within a try-catch block to capture other exceptions that occur while closing the Scanner class. An example of an exception that can occur while closing the scanner method is the illegalStateException which occurs when the close method is called at an incorrect time. The following code shows how the Scanner can be closed correctly.

Correct way of closing the Scanner class

Figure 5: Correct way of closing the Scanner class.

What are the consequences of not closing a Scanner?

The unclosed Scanner leads to memory leakage due to uncollected garbage on the Scanner object. This shall lead to misallocation of the memory thus increasing the usage of the computer memory and slowing down the processes. Closing the scanner leads to appropriate memory management thus avoiding memory leaks smoothening the running of processes in the program.

Can you close a Scanner in a try-with-resources block?

In try -with -resources the resources that are supposed to be used in the try block are declared and then they shall all be closed after the block is executed. There is no need to have the close method since all the resources shall be closed after the execution.

The post How to Close Scanner in JAVA appeared first on DoMyAssignments.com Blog: Writing Help, Topics & Tips.


View Entire Post

Read Entire Article