I am learning Java and working on some projects for fun. One of the problems that I have encountered is that when I use the Scanner object, Eclipse warns me that:
Resource Leak: Scan never closes.
So I added scan.close(); at the end of my code and takes care of the warning.
The problem arises because I have other classes in the same package that also use scanner objects, and Eclipse tells me to close the scanner in these classes accordingly. However, when I do this, it looks like it closes ALL scanner objects, and I get errors at runtime.
Here is an example of what causes the error:
import java.util.Scanner; public class test2 { public static void main(String [] args) { Scanner scan = new Scanner(System.in); int test = 0; do {
After the scanner is closed in the scanTest class and the do loop in test2 is entered again, in the line test = scan.nextInt();
I tried to move the creation of the scanner object to the do loop only to create a new object every time, but the error still occurs.
I donβt know why this is happening or how I can make sure that all the I / O objects are closed without problems.
One post I met mentioned that when System.in closed, I cannot open it again. If so, do I just need to make sure that the scanner object with System.in is closed at the very end of the program and @suppress are all the other scanner warnings in other classes? Or will it still leave all of these scanner objects open (bad)?
java java.util.scanner eclipse
Supercow
source share