我正在忙着制作一个计算器但不知道整数是不用的,我不知道为什么。我尝试修复它,但我无法找到如何做到这一点。我使用带有事件的按钮来计算答案,也许是出了问题。这是我的代码: 顺便说一句,我使用Eclipse
package cal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class cal{
//declare
JLabel l;
JButton calc = new JButton("Calculate");
JTextField f, f1;
String x, y, answer;
JTextArea a;
int answerValue, xValue, yValue;
//main
public static void main(String [] args){
cal c = new cal();
c.Start();
//Start method
}public void Start(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(640,640);
frame.setResizable(false);
//declare
l = new JLabel("enter value: ");
f = new JTextField(10);
f1 = new JTextField(10);
//remaining
JPanel p = new JPanel();
a = new JTextArea(20,50);
a.setEditable(false);
calc.addActionListener(new button());
p.add(l);
p.add(f);
p.add(f1);
p.add(calc);
p.add(a);
frame.getContentPane().add(p);
frame.setVisible(true);
}
// Calculate
class button implements ActionListener{
public void actionPerformed(ActionEvent e){
x = f.getText();
y = f1.getText();
//converting string to integer
try{
int xValue= Integer.parseInt(x);
int yValue = Integer.parseInt(y);
}catch( NumberFormatException exep){
exep.printStackTrace();
}
answerValue = xValue * yValue;
String AV =Integer.toString(answerValue);
System.out.println(answerValue);
//displaying answer
a.append(AV + "\n");
}
}
}
我说的是xValue和yValue
答案 0 :(得分:4)
这是问题所在:
try {
int xValue = Integer.parseInt(x);
int yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
宣布新的本地变量xValue
和yValue
,而不是更改实例变量xValue
和{的值{1}}。
如果您仍想要实例变量,只需更改代码以避免声明新的局部变量:
yValue
或者 - 最好,除非你真的需要别处 - 你可以完全摆脱实例变量,并在try / catch块之前声明局部变量:
try {
xValue = Integer.parseInt(x);
yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
同样,除非你在其他地方需要,否则你可以摆脱int xValue = 0;
int yValue = 0;
try {
xValue = Integer.parseInt(x);
yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
。
我强烈建议您重新考虑您的例外“处理”策略。你实际上忽略了这个例外而且只是继续好像一切都很好......
答案 1 :(得分:1)
当您尝试使用xValue
时,您实际上是在创建一个新的。与yValue
相同。
在您尝试访问名称之前删除名称前的int
,否则您将创建新名称,并使用它们。