I am having a lot of trouble with this code. The code compiled and ran as it was suppose to before I tried to put in the code to catch an exception. Then I could no longer get it to compile. It is suppose to catch an exception and produce an error message if the user inputs a negative number.
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
import java.io.IOException;
public class SquareRoot extends JFrame
{
public static void main(String[] args) {
//Creates Window
JFrame frame = new JFrame();
frame.setSize(450, 300);
frame.setTitle("Find the Square Root");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel Numberlbl = new JLabel("Enter a number:");
final JTextField NumberField = new JTextField(10);
NumberField.setText("");
JLabel Answerlbl = new JLabel("Square Root of your number is:");
final JTextField AnswerField = new JTextField(10);
AnswerField.setText("");
JLabel ButtonLabel = new JLabel("Calculate Square Root");
JButton button = new JButton("Find Square Root");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(Numberlbl);
panel.add(NumberField);
panel.add(ButtonLabel);
panel.add(button);
panel.add(Answerlbl);
panel.add(AnswerField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double NumberX = Double.parseDouble(NumberField.getText());
try
{
if(NumberX >=0);
}
catch(IOException e)
{
System.out.println("Number can not be negative.");
}
double Answer = Math.sqrt(NumberX);
AnswerField.setText(String.valueOf(Answer));
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You do not need try-catch to check negative, below should be enough. But you may need try-catch when you do formatting.
double noX = 0;
try {
noX = Double.parseDouble(NumberField.getText());
} catch(NumberFormatException e) {
System.out.println("Not a valid number");
}
if(noX < 0) {
System.out.println("Number can not be negative.");
}