TheMuffinMan TheMuffinMan - 29 days ago 8
Java Question

How to add int through JTextfield input

my code works fine except the fact I cannot obtain an accurate totalBill! Below is my code the area of issue is within the button_1 action. I am sure it is something simple with my math but the outcome for example if I input: 100 (FOR AMOUNT SPENT) 15 (FOR TOTAL TAX AMOUNT) and 10 (FOR TOTAL TIP AMOUNT) comes out to 123, just 2 short of being correct. For the life of me I have retried the fractional math and I am just stumped I am sure it is something relatively easy I just don't see it. Any help is much appreciated.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class unit6_Q2 extends JFrame {

JPanel main_1 = new JPanel();
JLabel main_2 = new JLabel();
JTextField question_1 = new JTextField("Enter amount here",30);
JTextField question_2 = new JTextField("Enter tax percent here", 30);
JTextField question_3 = new JTextField("Enter tip amount here", 30);
JButton button_1 = new JButton("Calculate");

public unit6_Q2() {
setTitle("Tutorial");
setVisible(true);
setSize(400,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);

main_1.add(question_1);
main_1.add(question_2);
main_1.add(question_3);

//if I want the use of enter on each TextField
/*
question_1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String input_1 = question_1.getText();
}
});

question_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input_2 = question_2.getText();
}
});
question_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input_2 = question_3.getText();
}
}); */

main_1.add(button_1);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input_1 = question_1.getText();
String input_2 = question_2.getText();
String input_3 = question_3.getText();
int amountSpent = Integer.parseInt(input_1);
int amountTaxed = Integer.parseInt(input_2);
int amountTipped = Integer.parseInt(input_3);

int totalTax = (int)(amountSpent * (amountTaxed*(1/100.0f)));
int totalTipped =(int)(amountSpent * (amountTipped*(1/100.0f)));
int totalBill = totalTipped + totalTax + amountSpent;
JOptionPane.showMessageDialog(null, totalBill);
}
});
add(main_1);
}
public static void main(String[] args) {

unit6_Q2 display = new unit6_Q2();
}
}

Answer

It is because you are truncating fractial data.

            int totalTax = (int)(amountSpent * (amountTaxed*(1/100.0f)));
            int totalTipped =(int)(amountSpent * (amountTipped*(1/100.0f)));

Use Math.round() insteed of (int) cast or simply stick to the floating points.

The way you are doing is if lets say totalTax would be 1.9, it will become 1 due to int cast.