I am trying to make a simple tax calculator program in Java, and cant seem to make the calculation work right. In the code I ended up having to turn the JTextField input into a double variable and then a string. For some reason, this does not work and brings up a bunch of errors. I know there must be some sort of simpler way to write this, so any ideas would be appreciated.
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));
}
}
}
}
The problem is you have declared
JTextField input;as a class variable but also created a local variable of the same name and added it to your JFrame. That is why you’re encountering aNullPointerExceptionwhen you performdouble fnum = Double.parseDouble(input.getText());