2011-10-26 30 views
1

我试图将“bonusStr”变量转换为双精度型,因此可以用于计算。但是,当试图编译时,我得到错误“变量bonusStr可能未被初始化”。我知道这是一个非常新鲜的问题,但任何帮助将不胜感激。Valriable可能没有被初始化?

非常感谢!

在几分钟内没有预料到会有这么多回复 - 我已经解决了这个问题。谢谢你们。 :-)

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; 
} 
} 

回答

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

由于错误状态bonusStr没有初始化(你没有影响的值),这样,直到它有一个价值,你不应该使用它里面Double.parseDouble

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

你从来就不是一个值设置为bonusStr - 默认情况下它会是null。在给它一个价值之前,你正在使用它。试试:

String bonusStr = "0"; 

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

0

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

相关问题