I have marked exactly where my error is occurring. I'm trying to check the contents of a textbox to see if the user entered a number. When I run the program, and click the "Calculate" button, I should get a JOptionPane error box. Instead, I get a long error in the command prompt starting with a NumberFormatException: empty string. Could someone please tell me why this is not being caught by strSquare.length?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
public class SquareRoots extends JFrame
{
public static void main(String[] args)
{
new SquareRoots();
}
private JPanel upper, middle, lower;
private JTextField entry, output;
private JButton calculate, close;
double dblSquare, result;
private String strSquare;
private int intSquare;
public SquareRoots()
{
super("Square Root Calculator");
ButtonListener b1 = new ButtonListener();
ButtonListener b2 = new ButtonListener();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
upper = new JPanel();
upper.setBorder(BorderFactory.createTitledBorder("Enter a number"));
upper.setLayout(new BorderLayout());
entry = new JTextField();
upper.add(entry, BorderLayout.CENTER);
middle = new JPanel();
middle.setBorder(BorderFactory.createTitledBorder("The Square Root is "));
//middle.setLayout(new FlowLayout(FlowLayout.CENTER));
middle.setLayout(new BorderLayout());
output = new JTextField();
middle.add(output, BorderLayout.CENTER);
lower = new JPanel();
lower.setLayout(new FlowLayout(FlowLayout.RIGHT));
calculate = new JButton("Calculate");
calculate.addActionListener(b1);
lower.add(calculate);
close = new JButton("Exit");
close.addActionListener(b2);
lower.add(close);
Container cp = getContentPane();
cp.add(upper, BorderLayout.NORTH);
cp.add(middle, BorderLayout.CENTER);
cp.add(lower, BorderLayout.SOUTH);
pack();
setVisible(true);
}
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == close)
{
System.exit(0);
}
if (e.getSource() == calculate)
{
String strSquare = entry.getText();
dblSquare = Double.valueOf(strSquare.trim()).doubleValue();
if (strSquare.length() == 0) //THIS IS NOT WORKING CORRECTLY
{
JOptionPane.showMessageDialog(
SquareRoots.this, "You didn't enter a number.",
"OOPS!", JOptionPane.INFORMATION_MESSAGE);
}
else
{
result = Math.sqrt(dblSquare);
output.setText(" " + result);
}
}
}
}
}