我正在尝试用 Java 制作一个简单的税收计算器程序,但似乎无法正确计算。在代码中,我最终不得不将 JTextField 输入转换为双变量,然后转换为字符串。出于某种原因,这不起作用并带来了一堆错误。我知道必须有某种更简单的方法来写这个,所以任何想法都会受到赞赏。
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.lang.*;
public class TaxCalculator extends JFrame {
String twelve;
JTextField input;
JLabel ans;
public TaxCalculator() {
JFrame frame = new JFrame("Tax Calculator");
JTextField input = new JTextField(10);
JLabel ans = new JLabel("");
JButton twelve = new JButton("12%");
frame.setVisible(true);
frame.setLayout(new FlowLayout());
frame.setSize(250, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Price of Item:"));
frame.add(input);
frame.add(ans);
frame.add(twelve);
twelve.addActionListener(new HandlerClass());
}
public static void main(String[] args) {
TaxCalculator calc = new TaxCalculator();
}
public class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent ae) {
double fnum = Double.parseDouble(input.getText());
if (ae.getSource() == twelve) {
fnum = (fnum / 0.12) + fnum;
ans.setText(Double.toString(fnum));
}
}
}
}