Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Help me figure out my logic error

Lynn Marciniak
Greenhorn
Posts: 7
I am a very green greenhorn. I am trying to create a tip calculator and I am having problems getting the correct math. I know that there are built in methods for the math, but I haven't gotten that far yet. My problem is that when I get to the total it is incorrect. The tip amount is right, but the total loses something in translation.

package Unit2;

//@author Lynn Marciniak
import javax.swing.*;

public class Assignment2_4 {

public static void main(String[] args){
String subttlString = JOptionPane.showInputDialog("Enter the subtotal with decimal point: ");
double subtotal = Double.parseDouble(subttlString);

String gratuityRateString = JOptionPane.showInputDialog("Enter the gratuity rate with decimal point: ");
double gratuityRate = Double.parseDouble(gratuityRateString);

double tipAmount = (int)(gratuityRate * subtotal * 100) / 100.0;

double total = (int)(tipAmount + subtotal * 100) /100.0;

String output = "The tip amount is: " + tipAmount + "\nThe total is: " + total;
JOptionPane.showMessageDialog(null, output);
}

}

Patrick Noah
Greenhorn
Posts: 28
First of all, don't multiply by 100 and then divide by 100, it makes the code harder to read. The reason you are not getting the right result is because you are casting to an int, which truncates the double.

Lynn Marciniak
Greenhorn
Posts: 7
Patrick Noah wrote:First of all, don't multiply by 100 and then divide by 100, it makes the code harder to read. The reason you are not getting the right result is because you are casting to an int, which truncates the double.

Thank you Patrick. When I went back and read the assignment, I was supposed to come up with the answer I came up without trying to format for money anyway. I was making it harder than it should have been.

Campbell Ritchie
Sheriff
Posts: 50277
80
Lynn Marciniak wrote:. . . I know that there are built in methods for the math, . . .
There aren't multiply() or add() methods. Not unless you use the BigDecimal class, which is the best for money calculations.