Reputation: 77
I'm having trouble with my Java code. It's not finished yet but I have an error telling me that the variable disRate has not been initialized but its has been in the else if statements.
This is an extra credit program for an Intro to Java class; it's an algorithm to calculate the final price for a discounted item based on the user's input of quantity and price.
import java.util.Scanner;
public class DiscountDemo {
public static void main(String[] args) {
// start code here
//variables
int quantity;
double itemPrice, totalCost, disRate, disCost, netAmount;
Scanner get = new Scanner(System.in);
//user prompt
System.out.print("Enter the quantity of an item: --> ");
quantity = get.nextInt();
System.out.print("Enter the price of an item: --> ");
itemPrice = get.nextInt();
//decision statements
if(quantity <= 0 || itemPrice <=0)
{
System.out.println("\nInvalid Data!\n");
}
else if(quantity <= 9)
{
disRate = 0;
}//if quantity <=9 end
else if(quantity >= 10 && quantity <= 19)
{
disRate = .1;
}//if quantity >=10 || <= 19 end
else if(quantity >= 20 && quantity <= 49)
{
disRate = .2;
}//if quantity >=20 || <= 49 end
else if(quantity >= 50 && quantity <=99)
{
disRate = .3;
}//if quantity >=50 || <= 99 end
else if(quantity >= 100)
{
disRate = .35;
}//if quantity >=100 end
//calculation
totalCost = quantity * itemPrice;
disCost = totalCost * disRate;
netAmount = itemPrice - disCost;
} //main end
} //class end
Upvotes: 0
Views: 53
Reputation: 1460
The problem is that you initialize disRate
only within a IF
statement and if all the boolean condition is false disRate
will be never initialized and the math on disCost = totalCost * disRate;
could be not be done.
The IDE detects this situation and asks you to initialize disRate
with a value.
Just do double disRate = 0;
at the start of your code or add a else
statement to initialize disRate
.
Upvotes: 4
Reputation: 427
You just declared it, not initialized. You do not have an else, just have if-elseif, of course that when the value is greater or equal to 100 will enter at the last if-else, but the compiler can not be so smarter.
} else if(quantity >= 50 && quantity <=99){
disRate = .3;
}else {
disRate = .35;
}
Upvotes: 0