扫描仪sc =新扫描仪(System.in) - 资源泄漏?

时间:2016-01-26 08:00:36

标签: java

以下是我正在搞乱的代码:

import java.util.*; public class Work {

public static void main(String[] args){
    System.out.println("Type 1 to convert from Farenheit to Celsius. Type 2 to convert from Farenheit to Kelvin.");
    Scanner sc = new Scanner(System.in);
    double x = sc.nextDouble();
    while ((x != 1) && (x != 2)){
    System.out.println("Please enter a value of either 1 or 2");
    x = sc.nextDouble();
    }

    if (x == 1){
        System.out.println("Enter the degrees in F and it will be converted to C:");
        double y = sc.nextDouble();
        double ans = convertoC(y);
        System.out.println(ans + " C");
    } else if (x == 2){
        System.out.println("Enter the degrees in F and it will be converted to K:");
        double v = sc.nextDouble();
        double ans = convertoK(v);
        System.out.println(ans + " K");
    } 
}


public static double convertoK(double x){
    return ((x + 459.67) * (5.0/9.0));
}

public static double convertoC(double x){
    return ((x - 32.0) * (5.0/9.0));
}

}

Eclipse告诉我扫描程序存在资源泄漏。我怎么能纠正这个? 此外,是否有更有效的方式接收输入呢?我觉得我的实现非常块,并且重复使用相同的代码。另外,我是否会使用try / catch来允许用户在没有输入数字的情况下重新输入另一个输入(因为它只会抛出异常)。

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要close()扫描仪,以便释放它所拥有的任何资源。理想情况下,这是在finally块中完成的,这样您就可以确保始终释放扫描仪累积的资源。

因此,您需要声明扫描程序:Scanner sc = null,然后将您方法的其余部分包装在try-catch块中。最后,添加finally块,其中关闭扫描仪(sc),前提是它不为空。

根据@Kevin Esche的评论,你也可以使用try-with-resources,它类似于C#的using指令。

您还在同一范围内的同一项目上声明了多个扫描仪。您在顶部声明的扫描仪应该足够,sxsy是不需要的。

相关问题