cannot assign value to “final” variable in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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())";"I am getting an error"不能为最终变量赋值。如果我从声明中删除单词final并使其与"int c"相同,那么在同一行中,我会得到一个错误"局部变量c不能从类中访问;需要声明为final"。有人能告诉我为什么会这样吗?
在函数中声明了C,然后在该函数中创建了一个匿名的内部类。这个内部类,即actionListener,在您的函数终止后仍然存在,所以它不能将值赋给C,因为C是该函数的本地类。
关于"final"的警告是误导性的——这只是编译器告诉您不能从匿名类访问瞬态局部变量。不能只通过使C成为final来解决这个问题,因为这会阻止对它进行任何赋值,但是可以使C成为pushButtonActionExecuted类的实例成员。像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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()); } }); } } |
我将跳过原因,直接讨论解决方案:使用
1 2 3 |
有关完整的故事,请参阅本帖。
but the line"c=Integer.parseInt(f.getText());" i am getting an error"cannot assign a value to a final variable
正确的。
A variable can be declared
final . Afinal variable may only be assigned to once. Declaring a variablefinal can serve as useful documentation that its value will not change and can help avoid programming errors.It is a compile-time error if a
final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.A blank
final is afinal variable whose declaration lacks an initializer.Once a
final variable has been assigned, it always contains the same value. If afinal variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
(他们的重点,不是我的。)
不要试图跟踪方法变量中存储在
这就是Java中存在关键字EDCOX1 0的原因。变量是最终变量,即其值不能更改。如果必须更改该值,请不要将变量标记为final。
编辑:
1 2 3 4 5 6 7 8 9 | but1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { c=Integer.parseInt(f.getText()); d.setVisible(false); d.dispose( ); } }); |
我相信这是导致编译器触发警告的代码段。你不能在这个类中使用
变量用final关键字声明意味着它的值不能更改。最后的变量和常量一样
只需从声明中删除