gpt4 book ai didi

java - 编译/捕获异常

转载 作者:行者123 更新时间:2023-12-02 07:56:10 27 4
gpt4 key购买 nike

我在使用这段代码时遇到了很多麻烦。在我尝试放入代码以捕获异常之前,代码按预期编译并运行。然后我就无法再编译它了。如果用户输入负数,它会捕获异常并产生错误消息。

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);

}
}

最佳答案

您不需要 try-catch 来检查是否定的,下面应该足够了。但格式化时可能需要 try-catch。

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.");
}

关于java - 编译/捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9613401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com