我有一個JavaFX 8程序(用於JavaFXPorts交叉平臺)非常框架以做我想做的事,但想出了一步。該程序讀取一個文本文件,對行進行計數以建立一個隨機範圍,從該範圍中選取一個隨機數並讀取該行以進行顯示。從lambda表達式引用的局部變量必須是最終的或有效的最終
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
解決此問題的最簡單方法是使用SimpleStringProperty而不是String來存儲'readln2'。 – eckig
謝謝。你能否詳細說明一下。從看它我不知道如何使它與我正在閱讀/使用外部文件的方式兼容。 – Jeff
在我看來,這個問題應該被削減到4行代碼。好吧,15行 - 它的Java畢竟! ;-)也許在這次減少練習中,答案會讓海報本身變得清晰。 –