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

1599534-20190307224741214-489631690.png

警告提示:资源泄露:‘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截图一张:
1599534-20190503235011131-758478455.png

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

转载于:https://www.cnblogs.com/venoms/p/10493172.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值