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

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\tSam and Ella's Delicatessen ");

  System.out.print("  What is the nome of the item: ");
  System.out.print("  What is the price of an item: ");
  System.out.print("Overnight delivery (0=no, 1=yes) : ");
  if (answer==0)
  else if (answer==1)
     System.out.println("  You entered wrong value. Try again: \n");



Recommended Answers

All 4 Replies

never mind ,got it

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

commented: Good explanation. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.