变量'number1'可能尚未初始化

时间:2015-01-20 10:00:15

标签: java variables initialization

我收到此错误Error:(100,22) java:variable number1 might not have been initializednumber2也是如此。这是我尝试在if语句中使用变量的时候。

当我宣布Variable 'number1' is never assigned时,number2public 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}}

2 个答案:

答案 0 :(得分:2)

必须初始化局部变量。

您需要初始化以下本地double变量。

double number1, number2, add, substract, multiply, divide;

答案 1 :(得分:2)

add = number1 + number2;

直到此行(以及所有后续行),您没有实例化,也没有为number1number2分配值。那么,JVM如何知道你想做什么?