我收到此错误Error:(100,22) java:variable number1 might not have been initialized
,number2
也是如此。这是我尝试在if
语句中使用变量的时候。
当我宣布Variable 'number1' is never assigned
时,number2
和public class event implements ActionListener {
public void actionPerformed (ActionEvent a) {
double number1, number2, add, substract, multiply, divide;
String operator = a.getActionCommand();
if (operator.equals("+")) {
add = number1 + number2;
result.setText(number1 + "+" + number2 + "=" + add);
result.setForeground(Color.RED);
}
else if (operator.equals("-")) {
substract = number1 - number2;
result.setText(number1 + "-" + number2 + "=" + substract);
result.setForeground(Color.RED);
}
else if (operator.equals("*")) {
multiply = number1 * number2;
result.setText(number1 + "*" + number2 + "=" + multiply);
result.setForeground(Color.RED);
}
else if (operator.equals("/")) {
if (number2 == 0) {
result.setText("Cannot divide by zero");
result.setForeground(Color.RED);
}
else {
divide = number1 / number2;
result.setText(number1 + "/" + number2 + "=" + divide);
result.setForeground(Color.RED);
}
}
}
}
再次相同。
将值设置为0将没有帮助,因为在最后一个if语句中该语句将始终为true。
{{1}}
答案 0 :(得分:2)
必须初始化局部变量。
您需要初始化以下本地double
变量。
double number1, number2, add, substract, multiply, divide;
答案 1 :(得分:2)
add = number1 + number2;
直到此行(以及所有后续行),您没有实例化,也没有为number1
和number2
分配值。那么,JVM如何知道你想做什么?