第五次修改

master
liwenjun 10 months ago
parent 981f4a0737
commit 45a0084ec9

@ -18,7 +18,7 @@ public class Calculator extends JFrame implements ActionListener {
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(6, 4, 10, 10)); // 修改为6行以容纳根号按钮
panel.setLayout(new GridLayout(5, 4, 10, 10)); // 修改为5行以适应新布局
String[] buttons = {
"7", "8", "9", "÷",
@ -29,11 +29,13 @@ public class Calculator extends JFrame implements ActionListener {
};
for (String text : buttons) {
if (!text.isEmpty()) { // 确保不创建空按钮
JButton button = new JButton(text);
button.setFont(new Font("Arial", Font.BOLD, 18)); // 增加按钮字体大小
button.addActionListener(this);
panel.add(button);
}
}
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@ -115,7 +117,11 @@ public class Calculator extends JFrame implements ActionListener {
try {
double num = Double.parseDouble(textField.getText());
result = Math.sqrt(num);
textField.setText(String.valueOf(result));
if (result == Math.floor(result)) { // 检查结果是否已经是整数
textField.setText(String.valueOf((int) result)); // 转换为整数并显示
} else {
textField.setText(String.valueOf(result)); // 否则显示浮点数
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入一个有效的数字");
}

Loading…
Cancel
Save