【发布时间】:2020-12-29 01:58:02
【问题描述】:
每当我尝试编译程序时,都会收到错误消息“在封闭范围内定义的局部变量迭代必须是最终的或有效的最终”。有谁知道如何解决这一问题?代码还没有完成,所以有些地方可能看起来不合适。
public static void go(purchase joe) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerNumberModel NumberImput =
new SpinnerNumberModel(1.00,0.00,null,1.00);
int iteration = 0;
JSpinner spinner = new JSpinner(NumberImput);
JLabel label = new JLabel("Please enter the price of the Item.");
JButton button = new JButton("Press here to continue");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
switch (iteration) {
case 0:
joe.setPrice((double)NumberImput.getNumber());
label.setText("Plese enter the amount that you are buying");
NumberImput.setValue(1.00);
iteration += 1;
break;
case 1:
joe.setAmount((int)NumberImput.getNumber());
label.setText("Plese enter the amount that you are buying");
break;
}
}
});
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(spinner);
frame.add(button);
frame.setSize(600, 500);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
joe.setPrice((double)NumberImput.getNumber());
}
【问题讨论】:
-
您在匿名类实现中使用方法级变量,例如“joe”、标签。作为一个动作监听器,你永远不知道它什么时候会被执行,因此我们在类范围内的任何变量的使用都应该是最终的。