繁体   English   中英

在Java中使用本地作用域中的非最终局部变量

[英]Use non-final local variable in local scope in Java

在我的下面的代码中,我使用了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时,它给出错误不能引用封闭范围中定义的非局部变量j。 如果我将j声明为final,则j不能递增。 在这里我需要使用j,所以任何人都可以帮我解决这个问题?

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

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();

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM