Jake H Jake H - 17 days ago 6
Java Question

Calculating a discount

I'm looking for a reason why this code will only use the 10% discount scenario listed below no matter what I input for the discountPercentage input message box. I need to make it so that the only percentages that will be calculated are 10%, 15%, or 25%. If a user enters anything else into the discountPercentage input message box, the discount will default to 10% off price 1.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class Assignment3 {

public static void main(String[] args) {
// Calculate the discount price of an item

// Convert price to display as decimal format
DecimalFormat df = new
DecimalFormat("#,###,##0.00");

// Declare discountPercentage variable


// Display message boxes for price and percentage entries
double price1 = Double.parseDouble(JOptionPane.showInputDialog( null, " Enter item price (ex:2.35): "));
double discountPercentage = Double.parseDouble(JOptionPane.showInputDialog( null, " Enter discount percentage "));
int dicountPercentage = 0;

// Declare if else statements for output calculations
if (discountPercentage > 25){

JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .10 * price1));

}else if (dicountPercentage == 25){

JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .25 * price1));

} else if (discountPercentage > 15){

JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .10 * price1));

} else if (dicountPercentage == 15){

JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .15 * price1));

} else if (discountPercentage >= 10){

JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .10 * price1));

}
}


Thanks

Answer

Your code will use the 10% scenario every time because in all the conditions on discountPercentage, you use the value .10, this exact same line every time:

       JOptionPane.showMessageDialog(null, " The discounted price is: " + "$" + df.format(price1 - .10 * price1));

That is, in all these conditions you have that same line:

       if (discountPercentage > 25){
       } else if (discountPercentage > 15){
       } else if (discountPercentage >= 10){

Also note that you have two variables in this code with almost the same name:

  • dicountPercentage
  • discountPercentage

And the first variable is set 0 and never changes, so all the conditions using dicountPercentage are pointless. And this kind of naming is very bad: avoid using variables with very similar names. (At first I didn't even notice there were two variables, I thought both are one and the same...)