Answer the question
In order to leave comments, you need to log in
Why is the input not closing and is Java resources leaking?
Hi guys.
I wrote a simple console input program, console output in netBeans and everything seems to be fine.
But when I open the file in Visual Studio Code, it says:
[Java] Resource leak: 'input' is never closed [536871799]
Scanner input - readingconsoleinputconsoleoutput.ReadingConsoleInputConsoleOutput.main(String[])
Resource leak: 'input' never closes
Scanner input - readconsoleinputconsoleoutput.ReadingConsoleInputConsoleOutput.main(String[])
package readingconsoleinputconsoleoutput;
import java.util.Scanner;
public class ReadingConsoleInputConsoleOutput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
String surName;
int yearBorn;
int yearNow;
System.out.print("Your name:");
name = input.nextLine();
System.out.print("Your middle name:");
surName = input.nextLine();
System.out.print("What is the year now?");
yearNow = input.nextInt();
System.out.print("What year were you born?");
yearBorn = input.nextInt();
System.out.print("Hello, "+name+" "+surName+" ");
System.out.print("Your age: "+(yearNow-yearBorn)+"");
}
}
Answer the question
In order to leave comments, you need to log in
You must close the scanner when you have finished reading.
According to the modern approach (since JDK 7) it should be wrapped in try...catch with auto-closing of resources:
String name;
String surName;
int yearBorn;
int yearNow;
try (Scanner input = new Scanner(System.in)) { // input автоматически закроется
System.out.print("Your name:");
name = input.nextLine();
System.out.print("Your middle name:");
surName = input.nextLine();
System.out.print("What is the year now?");
yearNow = input.nextInt();
System.out.print("What year were you born?");
yearBorn = input.nextInt();
System.out.print("Hello, "+name+" "+surName+" ");
System.out.print("Your age: "+(yearNow-yearBorn)+"");
} catch(Exception e) {
//Обработка исключения, если возникло.
e.printStackTrace();
}
Scanner input = new Scanner(System.in);
try {
...
} catch(Exception e) {
e.printStackTrace();
} finally {
input.close(); // Закрываем
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question