# final calculation after if statment

• October 23rd, 2011, 07:55 AM
spongyballs
final calculation after if statment
good evening peoples

Once again I am on top of my head if anyone could point me in the right direction I would be very grateful.

As you can see from snippet of code below I can chooce 1 of the following items (i have to pick 3 items so have the below done 3 times it works I am not to use loops yet)
the problem is at the end of picking my products it should add up total. It dosent seem to do that without the ifs, if else it will. I have tryed putting the nested if I press 1 for apples then it just makes me take strawberries ..... thinking about this all day in work and its now 4.45 am

System.out.println();
System.out.println("1. Apples");
System.out.println("2. Oranges");
System.out.println("3. Straberries");
System.out.println("4. Patato");
System.out.println("5. Turnips");
System.out.println("6. Carrots");

fruit = in.nextInt();
if (fruit <=1)
{
System.out.println ("Super choice");
System.out.print("Enter quantity of apples required ");
aQuantity = in.nextInt();
appleCost = aPrice * aQuantity; //calculate final cost by adding tax
String fs1 = String.format(" your apples will cost you: %.2f", appleCost);
System.out.println(fs1);
}

else if (fruit <=2){

System.out.print("Enter quantity of oranges required ");
oQuantity = in.nextInt();
orangesCost = oPrice * oQuantity; //calculate final cost by adding tax
String fs2 = String.format(" your oranges will cost you: %.2f",orangesCost);
System.out.println(fs2);
}
else if (fruit <=3){

this is what im getting
System.out.println(+appleCost + carrotCost+
5 errors found:
File: C:\Users\
Error: variable appleCost might not have been initialized
File: C:\Users\
Error: variable carrotCost might not have been initialized

How do i initalize appleCost ect if its inside an if and it needs user input????
• October 23rd, 2011, 12:47 PM
KevinWorkman
Re: final calculation after if statment
I can only guess, since you haven't provided all of the code (in SSCCE form), but that error pretty much says it all. You're using a variable that might not have been initialized. For example, if you choose oranges, what will the value of apples be? Keep in mind that local variables do not have a default value.
• October 23rd, 2011, 01:47 PM
Henry518
Re: final calculation after if statment
Pretty much what Kevin said. When you declare the variable "appleCost" im guessing your code says
Code :

`int appleCost;`
try putting
Code :

`int appleCost = 0;`