簡體   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