+ 1
Error: Basic Concepts:Getting User Input
Hi all. just starting out with Java. Online the code for this lesson works fine in the "code playground", (Scanner myVar = new Scanner(System.in)){ System.out.println(myVar.nextLine());} but when I plug it into Eclipse IDE for Java I get an compile error of "Resource leak: 'in' is never closed". I did some searching on google and found that I needed to wrap the scanner in "try" to get it to work. try(Scanner myVar = new Scanner(System.in)){ System.out.println(myVar.nextLine()); } Is this a version difference between the code playground versus what I have in Eclipse IDE? Or is there something more that I am missing? Thank you
4 ответов
+ 4
In your first code you may need to add myVar.close() towards the end of its scope to close the scanner. If that doesn't work, i'd need to see the code in its entirety. The second version is a try with resources. When using a try with resources the resourses within () after the keyword try are automatically handled and closed/freed up at the end of the try block, so calling .close() wouldn't be needed. try with resources is available as of Java 7.
+ 4
@Dr. Brown that's correct. It should work fine for this program, but in a larger program you should always try to free up your resources when you are finished with them. The IDE warning is trying to help remind you of this by complaining. If this code was within a loop or a method that was called repeatedly it may lead to a memory leak issue since the resource would not be freed up correctly and may not be garbage collected until the program is closed.
+ 1
You don't need the try block with the Scanner!
Just type:
Scanner myVar = new Scanner(System.in);
System.out.println(myVar.nextLine());
0
@ChaoticDawg - Thank you. Digging a bit more with your info. The compiler without the 'try' compiles, but complains that the scanner is not closed. The code still works. Looks like just a compiler warning in reality. MyVar in the eclipse IDE warns that is never closed. You don't see that warning in the online 'code playground.' I might be being to picky in comparing the IDE to the online compiler.
Full code block
import java.util.Scanner;
public class Mymain {
public static void main(String[ ] args) {
Scanner myVar = new Scanner(System.in);
System.out.println(myVar.nextLine());
}
}