第四次修改

master
zyn 10 months ago
parent 225befaf51
commit 981f4a0737

@ -18,14 +18,14 @@ public class Calculator extends JFrame implements ActionListener {
add(textField, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 4, 10, 10)); // 增加网格布局的间距
panel.setLayout(new GridLayout(6, 4, 10, 10)); // 修改为6行以容纳根号按钮
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"7", "8", "9", "÷",
"4", "5", "6", "×",
"1", "2", "3", "-",
"C", "0", ".", "+",
"="
"√", "=", ""
};
for (String text : buttons) {
@ -37,7 +37,7 @@ public class Calculator extends JFrame implements ActionListener {
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 600); // 设置窗口大小为宽800像素高500像素
setSize(400, 600); // 修改窗口大小为宽400像素高600像素以适应新布局
setLocationRelativeTo(null); // 窗口居中显示
pack();
setVisible(true);
@ -62,8 +62,8 @@ public class Calculator extends JFrame implements ActionListener {
break;
case "+":
case "-":
case "*":
case "/":
case "×":
case "÷":
if (!calculating) {
result = Double.parseDouble(textField.getText());
operator = command;
@ -75,6 +75,9 @@ public class Calculator extends JFrame implements ActionListener {
calculate(Double.parseDouble(textField.getText()));
}
break;
case "√":
calculateMathFunction();
break;
}
}
}
@ -87,10 +90,10 @@ public class Calculator extends JFrame implements ActionListener {
case "-":
result -= n;
break;
case "*":
case "×":
result *= n;
break;
case "/":
case "÷":
if (n != 0) {
result /= n;
} else {
@ -108,6 +111,17 @@ public class Calculator extends JFrame implements ActionListener {
calculating = true;
}
private void calculateMathFunction() {
try {
double num = Double.parseDouble(textField.getText());
result = Math.sqrt(num);
textField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入一个有效的数字");
}
calculating = true;
}
public static void main(String[] args) {
new Calculator();
}

Loading…
Cancel
Save