gpt4 book ai didi

java - 在 Java 的局部范围内使用非最终局部变量

转载 作者:行者123 更新时间:2023-11-29 05:06:13 24 4
gpt4 key购买 nike

在我下面的代码中,我使用了 j 变量,它是非最终局部变量

for (int j = 0; j < 4; j++) {

if (videoCapture[j].isOpened()) {
panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
mat = new Mat();
videoCapture[j].read(mat);
BufferedImage image = Mat2BufferedImage(mat);
g.drawImage(image, 0, 0, this);
repaint();
}
};
}

在我上面的代码中,我不能在 videoCapture[j].read(mat) 中使用 j。当我使用 j 时,它给出错误 Can not reference the non local variable j defined in an enclosing scope. 如果我将 j 声明为 final,则 j 不能递增。在这里我需要使用j,所以任何人都可以帮助我解决这个问题?

最佳答案

有一个解决方法。使用 temp 变量。像这样:

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
final int val = i; // temp final variable
new Thread() {
public void run() {
System.out.println(val); //the compiler checks for val (and according to javac rules, val should be (and it is) final).
};
}.start();

}
}

关于java - 在 Java 的局部范围内使用非最终局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30295367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com