VScode中JAVA程序"Resource leak: 'sc' is never closed"问题解决

最近在学习java编程,关于安装与环境变量的配置将在后面的博客中详细介绍,本篇博客主要介绍在java在输入中出现"Resource leak: 'sc' is never closed"的警告。

测试代码如下:

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");
        }
    }
}

警告提示:资源泄露:‘sc’永不关闭。

这可能带来一些安全问题,那么要怎么解决这个问题呢?既然‘sc’没有关闭,那么我们只需要把‘sc’关闭就好了,此时需要在后面添加’sc.close();’就解决。

修改后代码如下:

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");
        }
    }
}

附API截图一张:

如有疑问请查询JAVA API(https://docs.oracle.com/javase/8/docs/api/index.html)
PS:本文仅属个人观点,如有不当之处请指正!

posted @ 2019-03-07 22:48  Vlary  阅读(7078)  评论(2编辑  收藏  举报