sách gpt4 ai đã đi

java - 编译/捕获异常

In lại 作者:行者123 更新时间:2023-12-02 07:56:10 28 4
mua khóa gpt4 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());
thử
{
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);

}
}

1 Câu trả lời

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

double noX = 0;
thử {
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/

28 4 0
Bài viết được đề xuất: java - 我的 If 语句强制关闭
Bài viết được đề xuất: java - 如何从 github 构建其他人的项目?
Bài viết được đề xuất: java - 如何验证 jtable 中的列只能接受手机号码?
Bài viết được đề xuất: java - 简单博客中的 JSf 请求范围
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com