Home > Back-end >  What is wrong with this code? I am trying to make a program that computes tax and tips and ran into
What is wrong with this code? I am trying to make a program that computes tax and tips and ran into

Time:09-16

I feel like I am missing some form of conversion. I am still new to Java so I don't know much about it. Please help.

public static void main(String[] args){
    String mealCharge;
    double tax;
    double tip;
    double total;
    

    tax = mealCharge * 0.0625; //food tax is 6.25%
    tip = mealCharge * 0.15; //tip is 15%
    total = mealCharge   tax   tip;

    mealCharge = JOptionPane.showInputDialog("Please enter the charge for the meal.");
    JOptionPane.showMessageDialog(null, "Your total will be $"   total ".");

    
}

}

CodePudding user response:

In your code mealCharge is a String data type. But you can't use String type in the calculations. You need to convert mealCharge to the double/int/float/large/short data type. I assume, you need it to be a double type.

So, what I did I create a new variable for user input String mealChargeInput and new variable double mealCharge;. And then I convertend string to double by using Integer.parseInt() method.

Here's the code:

public static void main(String[] args) {
    String mealChargeInput; //Create a different name for "mealCharge" string
    double mealCharge;
    double tax;
    double tip;
    double total;

    mealChargeInput = JOptionPane.showInputDialog("Please enter the charge for the meal.");
    System.out.println(mealChargeInput.getClass().getSimpleName());
    mealCharge =  Double.parseDouble(mealChargeInput); // Convert string value of "mealChargeInput" to the double value and assign it to a new double variable

    tax = mealCharge * 0.0625; //food tax is 6.25%
    tip = mealCharge * 0.15; //tip is 15%
    total = mealCharge   tax   tip;


    JOptionPane.showMessageDialog(null, "Your total will be $"   total  "."); //Missing " " operator;


}

Is it what you need?

CodePudding user response:

You cant multiply a string (ie, mealCharge) with Double(ie, tip/tax). Change your datatype of the mealCharge to Double and you are good to go.

CodePudding user response:

From your code, I believe you will need to convert variable into the same type. As string mealcharge can not be * with a double - other data types. You would have to convert it into the same type depending on what you would want - in this case would be double.

  •  Tags:  
  • java
  • Related