我有一个JavaFX 8程序(适用于JavaFXPorts交叉平台),它实际上是为了做我想做的事情,但却是一步之遥.程序读取文本文件,对行进行计数以建立随机范围,从该范围中选取一个随机数并读取该行以进行显示.
The error is: local variables referenced from a lambda expression must be final or effectively final
button.setOnAction(e -> l.setText(readln2));
我对java有点新,但似乎我是否使用Lambda或者没有在Label l中使用下一个随机行显示我的button.setOnAction(e – > l.setText(readln2)); line期望静态值.
我每次按下屏幕上的按钮时,如何调整我所拥有的只是简单地显示var readln2的下一个值的任何想法?
在此先感谢,这是我的代码:
String readln2 = null;
in = new BufferedReader(new FileReader("/temp/mantra.txt"));
long linecnt = in.lines().count();
int linenum = rand1.nextInt((int) (linecnt - Low)) + Low;
try {
//open a bufferedReader to file
in = new BufferedReader(new FileReader("/temp/mantra.txt"));
while (linenum > 0) {
//read the next line until the specific line is found
readln2 = in.readLine();
linenum--;
}
in.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
Button button = new Button("Click the Button");
button.setOnAction(e -> l.setText(readln2));
// error: local variables referenced from a lambda expression must be final or effectively final
解决方法:
您只需将readln2的值复制到最终变量中即可:
final String labelText = readln2 ;
Button button = new Button("Click the Button");
button.setOnAction(e -> l.setText(labelText));
如果你想每次都获取一个新的随机行,你可以缓存感兴趣的行并在事件处理程序中选择一个随机行:
Button button = new Button("Click the button");
Label l = new Label();
try {
List lines = Files.lines(Paths.get("/temp/mantra.txt"))
.skip(low)
.limit(high - low)
.collect(Collectors.toList());
Random rng = new Random();
button.setOnAction(evt -> l.setText(lines.get(rng.nextInt(lines.size()))));
} catch (IOException exc) {
exc.printStackTrace();
}
// ...
或者您可以在事件处理程序中重新读取该文件.第一种技术(更快)但可能消耗大量内存;第二个不会将任何文件内容存储在内存中,但每次按下按钮时都会读取文件,这可能会使UI无响应.
你得到的错误基本上告诉你出了什么问题:你可以从lambda表达式中访问的唯一局部变量是final(声明为final,这意味着它们必须被赋值一次)或“有效final”(这基本上意味着)你可以让它们最终完成而不需要对代码进行任何其他更改).
您的代码无法编译,因为readln2被多次赋值(在循环内),因此无法将其声明为final.因此,您无法在lambda表达式中访问它.在上面的代码中,lambda中访问的唯一变量是l,lines和rng,它们都是“有效的最终”,因为它们只被赋值一次.(你可以将它们声明为final,代码仍然可以编译.)
标签:java,lambda
来源: https://codeday.me/bug/20191007/1868508.html