Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help me figure out my logic error

 
Lynn Marciniak
Greenhorn
Posts: 7
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic