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:本文仅属个人观点,如有不当之处请指正!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM