0

My BlueJ IDE is showing this error when I try to compile the class. I can't see what I'm doing wrong.

enter image description here

EnKrypt
  • 777
  • 8
  • 23
ninopino1
  • 11
  • 1
  • 1
  • 4

4 Answers4

2

If the condition in the if clause is not true, the variable is not assigned. In this case, the return that follows references an uninitialized variable.

Arthur Dent
  • 785
  • 3
  • 7
2

Before you can use a variable inside your if block , you need to initialize it.

Try this :

double albedo=0;

Instead of :

double albedo;

Keep in mind though that your variable will remain 0 if your condition returns false as you haven't specified an else block.

EnKrypt
  • 777
  • 8
  • 23
  • 2
    This makes the compilation error go away, but is misleading and does not really address the original logic problem. It is not necessary to initialize a Java variable at the point of declaration. It is necessary to assign a value before you try to use the value. There are two code paths here, one that visits the inside of the if block and one that doesn't. When the if condition is true, a value is assigned, otherwise not. The "otherwise not" was causing the compilation error. By the way, the if condition can never be true here since no number is both less than -50 and greater than +50. – Arthur Dent May 31 '13 at 00:13
1

This is a private method and local variables don't get default values, they have to be initialized. Consider a case where control doesn't go inside if block, then your variable contains no value, hence the error.

Rishikesh Dhokare
  • 3,559
  • 23
  • 34
0

Local variables should be initialized with value before using it .Something like this :

  double albedo = 0.0;

The compiler complains because local variables are not assigned any value by default. So at run time if the if() condition fails then the variable will not be assigned any value and in that case what value should the run time return back to the caller of the function ? Hence initialize it with some default value.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Just read this answer, and it explains why the error was caused perfectly, thank you so much for the clear explanation, I can't believe I didn't think of that! – ninopino1 May 27 '13 at 12:49