wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Help me figure out my logic error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help me figure out my logic error" Watch "Help me figure out my logic error" New topic
Author

Help me figure out my logic error

Lynn Marciniak
Greenhorn

Joined: Sep 04, 2011
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

Joined: Aug 22, 2011
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

Joined: Sep 04, 2011
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

Joined: Oct 13, 2005
Posts: 39084
    
  23
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.
 
GeeCON Prague 2014
 
subject: Help me figure out my logic error