I'm trying to understand the switch
statement.
So I have this problem which I solved already.
"A software company sells a package that retails for $99. Quantity discounts are given
according to the following:
10-19 = 20%
20-49 = 30%
50-99 = 40%
100 or more = 50%
Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total Amount of the purchase after the discount.
I solved it using an if
else if
structure and a couple relational operators, it looks like this
//Determine total price based on discounts
if (x >= 10 && x <= 19)
{
total = (((x*99) - (x * 99)* .2));
JOptionPane.showMessageDialog(null, "Your total is $" + total
+ " with a 20% discount");
}
else if(x >= 20 && x <= 49)
{
total = (((x*99) - (x * 99)* .3));
JOptionPane.showMessageDialog(null, "Your total is $" + total
+ " with a 30% discount.");
.
.
.
I would like to know if its possible to store the possible range of numbers in a single variable and then use it in for the case
statements? Would it make sense to use the switch
statement in this case? I tried fitting the range of possible numbers(essentially an expression, stored in a variable declared as Boolean
) in a variable but since I declared the variable(x) the parsed Integer
value of the whatever number the user inputs for the JOptionPane
input dialog box it won't let me use a boolean variable. So I'm still a bit confused on how exactly the switch
statement works, but I would appreciate any help on what goes and what doesn't when using a switch
statement.