Hi guys
I started to learn java and have a little problem\. When I try to compile my little program it says :

assgn2.java:40: variable overnight might not have been initialized
System.out.println(overnight);

How is that?

The code:

import java.io.*;

public class assgn2
{
 public static void main(String[] args) throws IOException
 {
  BufferedReader value=new BufferedReader(new InputStreamReader(System.in));
  String item,itemPrice,ans;
  double price,overnight;
  int answer;

  System.out.println("\n\t*********************************************");
  System.out.println("\n\t\tSam and Ella's Delicatessen ");
  System.out.println("\n\t*********************************************");

  System.out.print("  What is the nome of the item: ");
  item=value.readLine();
  System.out.print("  What is the price of an item: ");
  itemPrice=value.readLine();
  price=Double.parseDouble(itemPrice);
  do
  {
  System.out.print("Overnight delivery (0=no, 1=yes) : ");
  ans=value.readLine();
  answer=Integer.parseInt(ans);
  if (answer==0)
  {
   overnight=5.00;
   break;
  }
  else if (answer==1)
    {
     overnight=0.00;
     break;
    }
    else
     System.out.println("  You entered wrong value. Try again: \n");
  }while((answer!=1)||(answer!=0));

  System.out.println(overnight);
 }
}

thx

Good, can you mark this as solved then?
There would be link bellow last post which read something like "Marks Solved"...

You should post the solution even if you solved it yourself to help others potentially having the same issues.


Solution: Local variables need to be initialized with a value when declared.

Actually, that isn't the solution.

The way you say it makes it look like you have to do it right away.

However, the problem was that he declared a variable and wanted to print it out at the end.
His program had three different flows of which two did initialize the variable. The last flow option didn't. The idea is that between the declaration and it's use, it needs to be initialized, so not necessarilly at the same moment as the declaration.

In this case, it's a common error, because you know the loop won't end untill the variable gets its value. However, java doesn't know that, because your while loop checks other variables instead of the uninitialized one. Therefor, theoretically there still remains one path from declaration to first use which didn't initialize.

Ok, long answer for a fairly simple problem.

Black Box

Comments
Good explanation.
This question has already been answered. Start a new discussion instead.