无法为“最终”指定值java中的变量 [英] cannot assign value to "final" variable in java

查看:604
本文介绍了无法为“最终”指定值java中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
{
    final int c=0;
    final JDialog d=new JDialog();
    JLabel l=new JLabel("Enter the Element :");
    JButton but1=new JButton("OK");
    JButton but2=new JButton("Cancel");
    final JTextField f=new JTextField(10);
    JPanel panel = new JPanel();
    but1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            c=Integer.parseInt(f.getText());
            d.setVisible(false);
            d.dispose( );
        }
     });
but2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        d.setVisible(false);
        d.dispose( );
    }
});
}

我使用的是netbeans 7.1.1。这是我的代码,我已将'c'声明为final int,但行c = Integer.parseInt(f.getText());我收到错误无法为最终变量赋值。如果我从声明中删除单词final并将其作为int c,则在同一行中我得到一个错误无法从类中访问局部变量c;需要声明为final。谁能告诉我为什么会这样?

I am using netbeans 7.1.1. This is my code here i have declared 'c' as "final int" but the line "c=Integer.parseInt(f.getText());" i am getting an error "cannot assign a value to a final variable". If i am deleting the word final from the declaration and making it just as "int c" then in the same line i get an error "local variable c cannot be accessed from within a class;needs to be declared final". can anyone tell me why is this happening ?

推荐答案

你在一个函数中声明了 c ,然后你在该函数中创建了一个匿名内部类。这个内部类ActionListener会在函数终止之后持续存在 - 因此它无法为c赋值,因为c是函数的本地值。

You've got c declared in a function, and then you've created an anonymous inner class within that function. This inner class, the ActionListener, persists past the time your function terminates - so it can't assign values to c, because c is local to the function.

关于最终的警告具有误导性 - 这只是编译器告诉您无法从匿名类访问瞬态局部变量。你不能仅仅通过使c final成为问题来解决问题,因为这会阻止对它的任何赋值,但是你可以使用类pushButtonActionPerformed的实例成员来代替。这样的事情:

The warning about "final" is misleading - that's just the compiler telling you that you can't access transient local variables from an anonymous class. You can't solve the problem just by making c final, as that would prevent any assignment to it at all, but you can make c an instance member of the class pushButtonActionPerformed is in, instead. Something like this:

class Something
{
    int c;

    private void pushButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        JButton but1=new JButton("OK");
        but1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                c=Integer.parseInt(f.getText());
            }
        });
    }
}

这篇关于无法为“最终”指定值java中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆