变量可能尚未初始化?

时间:2011-10-26 14:13:05

标签: java variables initialization

我正在尝试将“bonusStr”变量转换为double,因此可以在计算中使用它。但是在尝试编译时,我得到错误“变量bonusStr可能尚未初始化”。我知道这是一个非常新手的问题,但任何给予的帮助都将受到赞赏。

非常感谢!

几分钟内没有期待这么多回复 - 我已经解决了这个问题。谢谢你们。 : - )

import static javax.swing.JOptionPane.*;
import java.text.DecimalFormat;

class Question3 {

public static void main(String[] args) {

    String intrestRateStr = showInputDialog("What is the interest rate?");    
        int intrestRate = Integer.parseInt(intrestRateStr);

    String depositStr = showInputDialog("How much will you deposit?"); 
        double depositAmount = Double.parseDouble(depositStr);

   DecimalFormat pounds = new DecimalFormat("£###,##0.00");

   double amountInterest = calcAmount(intrestRate, depositAmount); 

   String bonusStr;
          double bonus = Double.parseDouble(bonusStr);

   if (amountInterest >= 5000.00)
       bonus = (+100.00);
   else if (amountInterest >= 1000.00)
       bonus = (+50.00);


   double finalAmountInterestBonus = bonus + amountInterest;

    showMessageDialog(null, 
            "Your savings will become " + pounds.format(finalAmountInterestBonus));
}

private static double calcAmount(int intRate, double depAmount) {
    double result = depAmount*(1.0 + intRate/100.0);
    return result;
 }   
}

3 个答案:

答案 0 :(得分:1)

String bonusStr;
double bonus = Double.parseDouble(bonusStr);

由于错误状态bonusStr未初始化(您没有影响它的值),因此您不应在Double.parseDouble内使用它,直到它有值。

答案 1 :(得分:1)

   String bonusStr;
          double bonus = Double.parseDouble(bonusStr);

您永远不会将值设置为bonusStr - 默认情况下它将是null。您在给它一个值之前使用它。试试:

String bonusStr = "0";

最好给它一个默认值,比如0或者其他什么可以帮助你诊断你忘记给出一个合适的值。

答案 2 :(得分:0)

您的程序将引发NumberFormatException。你做一个没有值的字符串的parseDouble。在对其执行parseDouble之前,您必须使用值设置bonusStr。

相关问题