所以我在程序中遇到了这个错误:

BankChargesWilson.java:55: error: variable checksCost might not have been initialized
  System.out.println("Your total cost is " + money.format(checksCost) + ".");
                                                          ^
1 error


但是我不明白为什么当我创建格式化对象并更早地初始化了checksCost变量时。

这是对象+我的定义。

 // Decimal Format Object
  DecimalFormat money = new DecimalFormat("$##,###.##");

  // Scanner Object for Input
  Scanner keyboard = new Scanner (System.in);

  // Variables
  double baseFee = 10.00; // The base fee the bank requires for the account
  double checkFee; // The fee for a check
  int checksWritten; // The users inputted amount of checks written for the month
  double checksCost; // The cost for the checks based on the amount written in the month


这是我的else-if语句的使用位置,以及导致错误的输出和提示。

  if (checksWritten < 20)
  {
     checksCost = checksWritten * 0.10;
  }

  else if (checksWritten >= 20 && checksWritten <= 39)
  {
     checksCost = checksWritten * 0.08;
  }

  else if (checksWritten >= 40 && checksWritten <= 59)
  {
     checksCost = checksWritten * 0.06;
  }

  else if (checksWritten >= 60)
  {
     checksCost = checksWritten * 0.04;
  }

  System.out.println("You entered that you wrote " + checksWritten + " checks this month.");
  System.out.println("Your total cost is " + money.format(checksCost) + ".");


我不确定为什么要说它不再初始化了。

不过,问题是:checksCost是否仅在我的if-else-if循环范围内显示?如果是这样,那么在上面进一步定义时又会如何呢?

最佳答案

因为编译器没有像您想象的那样深入分析您的代码。

尽管您的if/else链肯定会根据其条件执行分支,但编译器无法实现此结果,编译器会抱怨您缺少else条件。

您可以通过初始化变量或将last else if设为简单的else(在这种情况下不会改变语义)来解决问题。

07-24 09:47
查看更多