第四次修改

master
zyn 10 months ago
parent 225befaf51
commit 981f4a0737

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

Loading…
Cancel
Save