0

Hey guys I am very new to programming I was practicing with a exercise question and I was doing the exercise I tried compiling the code that I already had typed, but it came back with year has not been initialized and the same error goes with investment. here is my code that I have right now. What am I doing wrong? by the way the variable future = investment * (1 + interest_rate)^year year is a exponent.

import java.lang.*;
public class Exercise63Page173

{

   public static void main(String [] args)
   {

   int year;
   double investment;
   final double INTEREST_RATE = .065;

   double future = investment * Math.pow((1 + INTEREST_RATE), year); 

   }


}
4

2 回答 2

3

Local method variables need to be initialized before used. You need to initialize your year and investment variables. Update the declaration to:

   int year = 0;
   double investment = 0.0d;

Note: Class or instance variables need not to be initialized as those are initialized by default but local variables need to be initialized.

于 2013-09-20T03:47:13.533 回答
0

In java all the data members will be initialized to their default value, that not the case with local variables. You need to initialize the local variable to some value before using them.

 int year = 0;
 double investment = 0.0d;

Even if you try following code still compiler will complain

    int i = 10, j = 10;
    int x;
    if(i==j) {
        x=0;
    }
    x++;

Compiler will complain because initialization of x is conditional. If you change the condition to if(true), compiler can see that xwill get some value before its use, so will not give error.

于 2013-09-20T03:49:38.897 回答