我是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? 谢谢你的帮助!
答案 0 :(得分:0)
除了关闭它之外,您没有以任何其他方式在keyb
内使用fact
。它完全不属于那里。计算n
的阶乘是纯函数,仅取决于n
而不是其他任何东西。
这可能是Eclipse中的一个错误。尝试将keyb
的声明移近其使用位置,即print("Pass value: ")
之后。