Tag Archives: “Resource leak: ‘sc’ is never closed”

Solution to the problem of Java program “resource leak: ‘SC’ is never closed” in vscode

Recently I am learning java programming. The configuration of installation and environment variables will be described in detail in the following blog. This blog mainly introduces the warning of “Resource leak:’sc’ is never closed” in java input.

The test code is as follows.

import java.util.*;
public class Print {
    public static void main(String[] args) {
        double num=0;;
        Scanner sc=new Scanner(System.in);
        num = sc.nextDouble();
        if(num == 1){
            System.out.println("1");
        }
        else{
            System.out.println("0");
        }
    }
}

Warning: resource leak:’sc’ will never be closed.

This may bring some security problems, so how to solve this problem? Since’sc’ is not closed, then we only need to close’sc’. At this time, we need to add’sc.close();’ to the end to solve it.

The modified code is as follows.

import java.util.*;
public class Print {
    public static void main(String[] args) {
        double num=0;;
        Scanner sc=new Scanner(System.in);
        num = sc.nextDouble();
        sc.close();
        if(num == 1){
            System.out.println("1");
        }
        else{
            System.out.println("0");
        }
     }
 }