从lambda表达式引用的局部变量必须是final或有效的final

我有一个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));行期望一个静态值。

有什么想法可以调整我必须在每次按下屏幕按钮时简单显示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

回答:

您可以将的值复制readln2final变量中:

    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<String> 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,这意味着它们必须被赋值一次)或“有效地最终”(基本上,这意味着您可以使它们成为最终版本,而无需对代码进行任何其他更改)。

您的代码无法编译,因为readln2多次(在循环内)分配了一个值,因此无法声明final。因此,您无法在lambda表达式中访问它。在上面的代码中,在lambda中访问的唯一变量是llinesrng,它们都是“有效的最终变量”,因为它们只被赋了一次值(您可以声明它们为最终变量,并且代码仍会编译。)

以上是 从lambda表达式引用的局部变量必须是final或有效的final 的全部内容, 来源链接: utcz.com/qa/430534.html

回到顶部