Issue
Whenever I type the scanner as a "nested line" it will warn me that [Resource leak: 'unassigned closeable value' is never closed] and advised me to add @SuppressWarnings("resource")
at top of it.
Is it right to just add the @SuppressWarnings("resource")
as it advised or there is another way which is more preferable?
public static void main(String [] args){
String name = new Scanner(System.in).nextLine();
System.out.printf("My name is %s", name);
}
Solution
Your IDE is likely warning you about not calling close()
, because Scanner
implements Closable
. As you don't want to close System.in
, suppress the warning, and forget about it. You can check your IDE's settings for what it should warn about (resource
). It is simply just not detecting that the scanner is using System.in
.
IntelliJ IDEA? You have probably enabled one or more of these:
Preferences -> Editor -> Inspections -> Resource management -> ...
Answered By - Andreas detests censorship
Answer Checked By - Cary Denson (JavaFixing Admin)