简体   繁体   中英

Use non-final local variable in local scope in Java

In my following code i used j variable which is non-final local variable

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

In my above code I can't use j in videoCapture[j].read(mat) . When I use j, it give error Can not refer to the non local variable j defined in an enclosing scope. If I declare j as final then j can't be increment. Here I need to use j, so any one can help me to resolve this problem?

There is a workaround . Use a temp variable. Like this :

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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