是否有必要在Block Lambda Expressions中关闭Scanner?

时间:2016-07-20 19:19:48

标签: java lambda java.util.scanner

我是Java中Lambda Expressions的新手,我不确定是否有必要在Block Lambda表达式中另外关闭Scanner:

public interface factorialInterface {
    int factorialMe (int n);
    }


import java.util.Scanner;
public class factorialDemo {
    public static void main(String args[]) {
        Scanner keyb = new Scanner (System.in);

        factorialInterface fact = (n) -> {
            int result = 1;

            for (int i = 1; i <= n; i++) {
                result = i * result;
            }
            keyb.close();  // <- not sure about this one.
            return result;
        };
        System.out.print("Pass value: ");
        System.out.println(fact.factorialMe(keyb.nextInt())); 
        System.out.println();


        keyb.close(); 

    }

}

如果我不关闭此块内的'keyb',Eclipse将告知我有关资源泄漏的信息。是否始终建议关闭Lambda Block内部的Scanner? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

除了关闭它之外,您没有以任何其他方式在keyb内使用fact。它完全不属于那里。计算n的阶乘是纯函数,仅取决于n而不是其他任何东西。

这可能是Eclipse中的一个错误。尝试将keyb的声明移近其使用位置,即print("Pass value: ")之后。