java - range of values in a switch statement -
this question has answer here:
i'm trying understand switch statement. have problem solved already. "a software company sells package retails $99. quantity discounts given according following:
10-19 = 20%
20-49 = 30%
50-99 = 40%
100 or more = 50%
write program asks user enter number of packages purchased. program should display amount of discount (if any) , total amount of purchase after discount.
i solved using if else if structure , couple relational operators, looks this
//determine total price based on discounts if (x >= 10 && x <= 19) { total = (((x*99) - (x * 99)* .2)); joptionpane.showmessagedialog(null, "your total $" + total + " 20% discount"); } else if(x >= 20 && x <= 49) { total = (((x*99) - (x * 99)* .3)); joptionpane.showmessagedialog(null, "your total $" + total + " 30% discount."); . . . i know if possible store possible range of numbers in single variable , use in case statements? make sense use switch statement in case? tried fitting range of possible numbers(essentially expression, stored in variable declared boolean) in variable since declared variable(x) parsed integer value of whatever number user inputs joptionpane input dialog box won't let me use boolean variable. i'm still bit confused on how switch statement works, appreciate on goes , doesn't when using switch statement.
how about
if(total >= 100) { //use 50% } else if(total >= 50) { //use 40% } else if(total >= 20) { //use 30% } else if(total >= 10) { //use 20% } else { //no discount } if reach else if total >= 50, know total < 100. , on. makes use of if..else if..else statement, when can infer conditions based on previous statements. code right equivalent if used if statements.
also
total = (((x*99) - (x * 99)* .2)); would better written as
total = x * 99 * (1-.2)
Comments
Post a Comment