鱼C论坛

 找回密码
 立即注册

地图设计

[复制链接]
发表于 2024-4-7 14:05:17 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-07 14:05
@FishC1 用Java完成该代码编写一个日记本功能的程序, ...


import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Diary {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入姓名:");
        String name = scanner.nextLine();
        System.out.print("请输入日期(格式:yyyy-MM-dd):");
        String date = scanner.nextLine();
        System.out.print("请输入天气:");
        String weather = scanner.nextLine();
        System.out.print("请输入日记标题:");
        String title = scanner.nextLine();
        System.out.print("请输入内容:");
        String content = scanner.nextLine();

        // 构造文件名
        String fileName = name + "日记本.txt";
        try (FileOutputStream fos = new FileOutputStream(fileName, true)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String currentTime = sdf.format(new Date());

            // 写入日记内容
            fos.write(("姓名:" + name + "\n").getBytes());
            fos.write(("日期:" + date + "\n").getBytes());
            fos.write(("时间:" + currentTime + "\n").getBytes());
            fos.write(("天气:" + weather + "\n").getBytes());
            fos.write(("标题:" + title + "\n").getBytes());
            fos.write(("内容:" + content + "\n").getBytes());
            fos.write("\n".getBytes());

            System.out.println("日记已保存至本地文件:" + fileName);
        } catch (IOException e) {
            System.out.println("保存失败:" + e.getMessage());
        }
    }
}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 13:54:44 | 显示全部楼层
@FishC1 利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 13:55:04 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 13:54
@FishC1 利用Java Swing 图形组件开发一个可以进行简 ...


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {
    private JTextField inputField; // 输入框
    private JButton[] numberButtons; // 数字按钮数组
    private JButton[] operatorButtons; // 运算符按钮数组
    private JButton equalButton; // 等号按钮
    private JButton clearButton; // 清除按钮

    public Calculator() {
        setTitle("简单计算器");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 初始化组件
        inputField = new JTextField();
        inputField.setHorizontalAlignment(JTextField.RIGHT);
        add(inputField, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 4));

        numberButtons = new JButton[10];
        for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
            buttonPanel.add(numberButtons);
        }

        operatorButtons = new JButton[4];
        operatorButtons[0] = new JButton("+");
        operatorButtons[1] = new JButton("-");
        operatorButtons[2] = new JButton("*");
        operatorButtons[3] = new JButton("/");
        for (int i = 0; i < 4; i++) {
            operatorButtons.addActionListener(this);
            buttonPanel.add(operatorButtons);
        }

        equalButton = new JButton("=");
        equalButton.addActionListener(this);
        buttonPanel.add(equalButton);

        clearButton = new JButton("C");
        clearButton.addActionListener(this);
        buttonPanel.add(clearButton);

        add(buttonPanel, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == clearButton) {
            inputField.setText(""); // 清空输入框
        } else if (source == equalButton) {
            String expression = inputField.getText(); // 获取输入表达式
            double result = calculate(expression); // 调用计算方法计算结果
            inputField.setText(String.valueOf(result)); // 显示结果
        } else {
            JButton button = (JButton) source;
            String text = button.getText();
            inputField.setText(inputField.getText() + text); // 在输入框中添加按钮上的数字或运算符
        }
    }

    // 计算表达式结果的方法
    private double calculate(String expression) {
        double result = 0;
        try {
            result = Double.parseDouble(expression);
        } catch (NumberFormatException e) {
            // 表达式不是一个数字,进行四则运算
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            try {
                result = (double) engine.eval(expression);
            } catch (ScriptException ex) {
                JOptionPane.showMessageDialog(this, "表达式错误!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator();
            }
        });
    }
}

这个示例使用了Java Swing库来创建一个简单的图形化计算器。计算器的界面包含一个文本字段和一些按钮,用于输入数字和执行运算。操作包括加、减、乘、除和等号。当用户点击等号按钮时,程序会获取文本字段中的表达式,并调用计算方法来计算结果,并在文本字段中显示结果。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 13:56:07 | 显示全部楼层
@FishC1通过用java 利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 13:56:42 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 13:56
@FishC1通过用java 利用Java Swing 图形组件开发一个 ...


当然可以!下面是一个简单的Java Swing图形化计算器示例代码:

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;

  5. public class Calculator extends JFrame implements ActionListener {
  6.     private JTextField textField;
  7.     private JButton[] numberButtons;
  8.     private JButton[] operatorButtons;
  9.     private JButton equalButton;
  10.     private JButton clearButton;
  11.     private String display = "";

  12.     public Calculator() {
  13.         setTitle("简单计算器");
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         setSize(300, 400);
  16.         setLocationRelativeTo(null);

  17.         textField = new JTextField();
  18.         textField.setPreferredSize(new Dimension(300, 50));
  19.         textField.setHorizontalAlignment(JTextField.RIGHT);

  20.         numberButtons = new JButton[10];
  21.         for (int i = 0; i < 10; i++) {
  22.             numberButtons[i] = new JButton(String.valueOf(i));
  23.             numberButtons[i].addActionListener(this);
  24.         }

  25.         operatorButtons = new JButton[4];
  26.         operatorButtons[0] = new JButton("+");
  27.         operatorButtons[1] = new JButton("-");
  28.         operatorButtons[2] = new JButton("*");
  29.         operatorButtons[3] = new JButton("/");
  30.         for (JButton button : operatorButtons) {
  31.             button.addActionListener(this);
  32.         }

  33.         equalButton = new JButton("=");
  34.         equalButton.addActionListener(this);

  35.         clearButton = new JButton("C");
  36.         clearButton.addActionListener(this);

  37.         setLayout(new GridLayout(5, 3));
  38.         add(textField);
  39.         for (JButton button : numberButtons) {
  40.             add(button);
  41.         }
  42.         for (JButton button : operatorButtons) {
  43.             add(button);
  44.         }
  45.         add(equalButton);
  46.         add(clearButton);

  47.         setVisible(true);
  48.     }

  49.     @Override
  50.     public void actionPerformed(ActionEvent e) {
  51.         if (e.getSource() == clearButton) {
  52.             display = "";
  53.         } else if (e.getSource() == equalButton) {
  54.             try {
  55.                 display = String.valueOf(eval(display));
  56.             } catch (ArithmeticException ex) {
  57.                 display = "错误";
  58.             }
  59.         } else {
  60.             display += ((JButton) e.getSource()).getText();
  61.         }

  62.         textField.setText(display);
  63.     }

  64.     public static double eval(final String str) {
  65.         return new Object() {
  66.             int pos = -1, ch;

  67.             void nextChar() {
  68.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  69.             }

  70.             boolean eat(int charToEat) {
  71.                 while (ch == ' ') {
  72.                     nextChar();
  73.                 }
  74.                 if (ch == charToEat) {
  75.                     nextChar();
  76.                     return true;
  77.                 }
  78.                 return false;
  79.             }

  80.             double parse() {
  81.                 nextChar();
  82.                 double x = parseExpression();
  83.                 if (pos < str.length()) {
  84.                     throw new RuntimeException("意外字符: " + (char) ch);
  85.                 }
  86.                 return x;
  87.             }

  88.             double parseExpression() {
  89.                 double x = parseTerm();
  90.                 for (; ; ) {
  91.                     if (eat('+')) {
  92.                         x += parseTerm();
  93.                     } else if (eat('-')) {
  94.                         x -= parseTerm();
  95.                     } else {
  96.                         return x;
  97.                     }
  98.                 }
  99.             }

  100.             double parseTerm() {
  101.                 double x = parseFactor();
  102.                 for (; ; ) {
  103.                     if (eat('*')) {
  104.                         x *= parseFactor();
  105.                     } else if (eat('/')) {
  106.                         x /= parseFactor();
  107.                     } else {
  108.                         return x;
  109.                     }
  110.                 }
  111.             }

  112.             double parseFactor() {
  113.                 if (eat('+')) {
  114.                     return parseFactor();
  115.                 }
  116.                 if (eat('-')) {
  117.                     return -parseFactor();
  118.                 }

  119.                 double x;
  120.                 int startPos = this.pos;
  121.                 if (eat('(')) {
  122.                     x = parseExpression();
  123.                     eat(')');
  124.                 } else if ((ch >= '0' && ch <= '9') || ch == '.') {
  125.                     while ((ch >= '0' && ch <= '9') || ch == '.') {
  126.                         nextChar();
  127.                     }
  128.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  129.                 } else {
  130.                     throw new RuntimeException("意外字符: " + (char) ch);
  131.                 }

  132.                 return x;
  133.             }
  134.         }.parse();
  135.     }

  136.     public static void main(String[] args) {
  137.         SwingUtilities.invokeLater(new Runnable() {
  138.             public void run() {
  139.                 new Calculator();
  140.             }
  141.         });
  142.     }
  143. }
复制代码


运行上述代码,将弹出一个简单的图形化计算器窗口,你可以在这个窗口中进行四则运算。希望对你有帮助!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:01:53 | 显示全部楼层
@FishC1对每行代码进行注释
  1.             int pos = -1, ch;

  2.             void nextChar() {
  3.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  4.             }

  5.             boolean eat(int charToEat) {
  6.                 while (ch == ' ') {
  7.                     nextChar();
  8.                 }
  9.                 if (ch == charToEat) {
  10.                     nextChar();
  11.                     return true;
  12.                 }
  13.                 return false;
  14.             }

  15.             double parse() {
  16.                 nextChar();
  17.                 double x = parseExpression();
  18.                 if (pos < str.length()) {
  19.                     throw new RuntimeException("意外字符: " + (char) ch);
  20.                 }
  21.                 return x;
  22.             }

  23.             double parseExpression() {
  24.                 double x = parseTerm();
  25.                 for (; ; ) {
  26.                     if (eat('+')) {
  27.                         x += parseTerm();
  28.                     } else if (eat('-')) {
  29.                         x -= parseTerm();
  30.                     } else {
  31.                         return x;
  32.                     }
  33.                 }
  34.             }

  35.             double parseTerm() {
  36.                 double x = parseFactor();
  37.                 for (; ; ) {
  38.                     if (eat('*')) {
  39.                         x *= parseFactor();
  40.                     } else if (eat('/')) {
  41.                         x /= parseFactor();
  42.                     } else {
  43.                         return x;
  44.                     }
  45.                 }
  46.             }

  47.             double parseFactor() {
  48.                 if (eat('+')) {
  49.                     return parseFactor();
  50.                 }
  51.                 if (eat('-')) {
  52.                     return -parseFactor();
  53.                 }

  54.                 double x;
  55.                 int startPos = this.pos;
  56.                 if (eat('(')) {
  57.                     x = parseExpression();
  58.                     eat(')');
  59.                 } else if ((ch >= '0' && ch <= '9') || ch == '.') {
  60.                     while ((ch >= '0' && ch <= '9') || ch == '.') {
  61.                         nextChar();
  62.                     }
  63.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  64.                 } else {
  65.                     throw new RuntimeException("意外字符: " + (char) ch);
  66.                 }

  67.                 return x;
  68.             }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:03:32 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:01
@FishC1对每行代码进行注释            int pos = -1, ...


下面是对每行代码进行注释的解释:

  1. int pos = -1, ch; // 初始化位置和字符变量

  2. void nextChar() { // 获取下一个字符
  3.     ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  4. }

  5. boolean eat(int charToEat) { // 检查并吃掉指定的字符
  6.     while (ch == ' ') {
  7.         nextChar();
  8.     }
  9.     if (ch == charToEat) {
  10.         nextChar();
  11.         return true;
  12.     }
  13.     return false;
  14. }

  15. double parse() { // 解析整个表达式
  16.     nextChar();
  17.     double x = parseExpression();
  18.     if (pos < str.length()) {
  19.         throw new RuntimeException("意外字符: " + (char) ch);
  20.     }
  21.     return x;
  22. }

  23. double parseExpression() { // 解析表达式中的加减法
  24.     double x = parseTerm();
  25.     for (;;) {
  26.         if (eat('+')) {
  27.             x += parseTerm();
  28.         } else if (eat('-')) {
  29.             x -= parseTerm();
  30.         } else {
  31.             return x;
  32.         }
  33.     }
  34. }

  35. double parseTerm() { // 解析表达式中的乘除法
  36.     double x = parseFactor();
  37.     for (;;) {
  38.         if (eat('*')) {
  39.             x *= parseFactor();
  40.         } else if (eat('/')) {
  41.             x /= parseFactor();
  42.         } else {
  43.             return x;
  44.         }
  45.     }
  46. }

  47. double parseFactor() { // 解析表达式中的因子
  48.     if (eat('+')) { // 处理正号
  49.         return parseFactor();
  50.     }
  51.     if (eat('-')) { // 处理负号
  52.         return -parseFactor();
  53.     }
  54.     double x; // 临时变量
  55.     int startPos = this.pos; // 记录起始位置
  56.     if (eat('(')) { // 处理括号
  57.         x = parseExpression();
  58.         eat(')');
  59.     } else if ((ch >= '0' && ch <= '9') || ch == '.') { // 处理数字
  60.         while ((ch >= '0' && ch <= '9') || ch == '.') {
  61.             nextChar();
  62.         }
  63.         x = Double.parseDouble(str.substring(startPos, this.pos));
  64.     } else {
  65.         throw new RuntimeException("意外字符: " + (char) ch);
  66.     }
  67.     return x;
  68. }
复制代码


这段代码实现了一个简单的四则运算解析器。它能够从一个字符串中解析出数学表达式,并计算结果。其中,parse()方法调用parseExpression()方法来解析整个表达式,parseExpression()方法又调用parseTerm()方法来解析加减法,parseTerm()方法又调用parseFactor()方法来解析乘除法。eat()函数用于检查和吃掉指定的字符。整个过程通过递归和循环来实现对表达式的解析和计算。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:04:25 | 显示全部楼层
@FishC1对每行代码进行注释
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. class Calculator extends JFrame implements ActionListener {
  6.     private JTextField textField;
  7.     private JButton[] numberButtons;
  8.     private JButton[] operatorButtons;
  9.     private JButton equalButton;
  10.     private JButton clearButton;
  11.     private String display = "";

  12.     public Calculator() {
  13.         setTitle("简单计算器");
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         setSize(300, 400);
  16.         setLocationRelativeTo(null);

  17.         textField = new JTextField();
  18.         textField.setPreferredSize(new Dimension(300, 50));
  19.         textField.setHorizontalAlignment(JTextField.RIGHT);

  20.         numberButtons = new JButton[10];
  21.         for (int i = 0; i < 10; i++) {
  22.             numberButtons[i] = new JButton(String.valueOf(i));
  23.             numberButtons[i].addActionListener(this);
  24.         }

  25.         operatorButtons = new JButton[4];
  26.         operatorButtons[0] = new JButton("+");
  27.         operatorButtons[1] = new JButton("-");
  28.         operatorButtons[2] = new JButton("*");
  29.         operatorButtons[3] = new JButton("/");
  30.         for (JButton button : operatorButtons) {
  31.             button.addActionListener(this);
  32.         }

  33.         equalButton = new JButton("=");
  34.         equalButton.addActionListener(this);

  35.         clearButton = new JButton("C");
  36.         clearButton.addActionListener(this);

  37.         setLayout(new GridLayout(5, 3));
  38.         add(textField);
  39.         for (JButton button : numberButtons) {
  40.             add(button);
  41.         }
  42.         for (JButton button : operatorButtons) {
  43.             add(button);
  44.         }
  45.         add(equalButton);
  46.         add(clearButton);

  47.         setVisible(true);
  48.     }

  49.     @Override
  50.     public void actionPerformed(ActionEvent e) {
  51.         if (e.getSource() == clearButton) {
  52.             display = "";
  53.         } else if (e.getSource() == equalButton) {
  54.             try {
  55.                 display = String.valueOf(eval(display));
  56.             } catch (ArithmeticException ex) {
  57.                 display = "错误";
  58.             }
  59.         } else {
  60.             display += ((JButton) e.getSource()).getText();
  61.         }

  62.         textField.setText(display);
  63.     }

  64.     public static double eval(final String str) {
  65.         return new Object() {
  66.             int pos = -1, ch;

  67.             void nextChar() {
  68.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  69.             }

  70.             boolean eat(int charToEat) {
  71.                 while (ch == ' ') {
  72.                     nextChar();
  73.                 }
  74.                 if (ch == charToEat) {
  75.                     nextChar();
  76.                     return true;
  77.                 }
  78.                 return false;
  79.             }

  80.             double parse() {
  81.                 nextChar();
  82.                 double x = parseExpression();
  83.                 if (pos < str.length()) {
  84.                     throw new RuntimeException("意外字符: " + (char) ch);
  85.                 }
  86.                 return x;
  87.             }

  88.             double parseExpression() {
  89.                 double x = parseTerm();
  90.                 for (; ; ) {
  91.                     if (eat('+')) {
  92.                         x += parseTerm();
  93.                     } else if (eat('-')) {
  94.                         x -= parseTerm();
  95.                     } else {
  96.                         return x;
  97.                     }
  98.                 }
  99.             }

  100.             double parseTerm() {
  101.                 double x = parseFactor();
  102.                 for (; ; ) {
  103.                     if (eat('*')) {
  104.                         x *= parseFactor();
  105.                     } else if (eat('/')) {
  106.                         x /= parseFactor();
  107.                     } else {
  108.                         return x;
  109.                     }
  110.                 }
  111.             }

  112.             double parseFactor() {
  113.                 if (eat('+')) {
  114.                     return parseFactor();
  115.                 }
  116.                 if (eat('-')) {
  117.                     return -parseFactor();
  118.                 }

  119.                 double x;
  120.                 int startPos = this.pos;
  121.                 if (eat('(')) {
  122.                     x = parseExpression();
  123.                     eat(')');
  124.                 } else if ((ch >= '0' && ch <= '9') || ch == '.') {
  125.                     while ((ch >= '0' && ch <= '9') || ch == '.') {
  126.                         nextChar();
  127.                     }
  128.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  129.                 } else {
  130.                     throw new RuntimeException("意外字符: " + (char) ch);
  131.                 }

  132.                 return x;
  133.             }
  134.         }.parse();
  135.     }

  136.     public static void main(String[] args) {
  137.         SwingUtilities.invokeLater(new Runnable() {
  138.             public void run() {
  139.                 new Calculator();
  140.             }
  141.         });
  142.     }
  143. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:05:08 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:04
@FishC1对每行代码进行注释import javax.swing.*;
im ...


下面是对每行代码进行注释的解释:

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;

  5. class Calculator extends JFrame implements ActionListener {
  6.     private JTextField textField;
  7.     private JButton[] numberButtons; // 数字按钮数组
  8.     private JButton[] operatorButtons; // 操作符按钮数组
  9.     private JButton equalButton;
  10.     private JButton clearButton;
  11.     private String display = "";

  12.     public Calculator() {
  13.         setTitle("简单计算器");
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         setSize(300, 400);
  16.         setLocationRelativeTo(null);

  17.         textField = new JTextField();
  18.         textField.setPreferredSize(new Dimension(300, 50));
  19.         textField.setHorizontalAlignment(JTextField.RIGHT);

  20.         numberButtons = new JButton[10];
  21.         for (int i = 0; i < 10; i++) {
  22.             numberButtons[i] = new JButton(String.valueOf(i));
  23.             numberButtons[i].addActionListener(this);
  24.         }

  25.         operatorButtons = new JButton[4];
  26.         operatorButtons[0] = new JButton("+");
  27.         operatorButtons[1] = new JButton("-");
  28.         operatorButtons[2] = new JButton("*");
  29.         operatorButtons[3] = new JButton("/");
  30.         for (JButton button : operatorButtons) {
  31.             button.addActionListener(this);
  32.         }

  33.         equalButton = new JButton("=");
  34.         equalButton.addActionListener(this);

  35.         clearButton = new JButton("C");
  36.         clearButton.addActionListener(this);

  37.         setLayout(new GridLayout(5, 3));
  38.         add(textField);
  39.         for (JButton button : numberButtons) {
  40.             add(button);
  41.         }
  42.         for (JButton button : operatorButtons) {
  43.             add(button);
  44.         }
  45.         add(equalButton);
  46.         add(clearButton);

  47.         setVisible(true);
  48.     }

  49.     @Override
  50.     public void actionPerformed(ActionEvent e) {
  51.         if (e.getSource() == clearButton) { // 清除按钮点击事件
  52.             display = "";
  53.         } else if (e.getSource() == equalButton) { // 等于按钮点击事件
  54.             try {
  55.                 display = String.valueOf(eval(display)); // 调用eval方法计算表达式结果
  56.             } catch (ArithmeticException ex) {
  57.                 display = "错误";
  58.             }
  59.         } else { // 数字按钮和操作符按钮点击事件
  60.             display += ((JButton) e.getSource()).getText();
  61.         }
  62.         textField.setText(display);
  63.     }

  64.     public static double eval(final String str) {
  65.         return new Object() {
  66.             int pos = -1, ch;

  67.             void nextChar() {
  68.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1; // 获取下一个字符
  69.             }

  70.             boolean eat(int charToEat) {
  71.                 while (ch == ' ') {
  72.                     nextChar(); // 跳过空格
  73.                 }
  74.                 if (ch == charToEat) {
  75.                     nextChar(); // 如果当前字符与目标字符匹配,则获取下一个字符
  76.                     return true;
  77.                 }
  78.                 return false;
  79.             }

  80.             double parse() {
  81.                 nextChar(); // 获取第一个字符
  82.                 double x = parseExpression(); // 解析表达式
  83.                 if (pos < str.length()) {
  84.                     throw new RuntimeException("意外字符: " + (char) ch); // 如果还有剩余字符,抛出异常
  85.                 }
  86.                 return x;
  87.             }

  88.             double parseExpression() {
  89.                 double x = parseTerm(); // 解析项
  90.                 for (; ; ) {
  91.                     if (eat('+')) { // 如果下一个字符是+,则解析下一项并相加
  92.                         x += parseTerm();
  93.                     } else if (eat('-')) { // 如果下一个字符是-,则解析下一项并相减
  94.                         x -= parseTerm();
  95.                     } else {
  96.                         return x;
  97.                     }
  98.                 }
  99.             }

  100.             double parseTerm() {
  101.                 double x = parseFactor(); // 解析因子
  102.                 for (; ; ) {
  103.                     if (eat('*')) { // 如果下一个字符是*,则解析下一个因子并相乘
  104.                         x *= parseFactor();
  105.                     } else if (eat('/')) { // 如果下一个字符是/,则解析下一个因子并相除
  106.                         x /= parseFactor();
  107.                     } else {
  108.                         return x;
  109.                     }
  110.                 }
  111.             }

  112.             double parseFactor() {
  113.                 if (eat('+')) { // 如果下一个字符是+,则解析下一个因子
  114.                     return parseFactor();
  115.                 }
  116.                 if (eat('-')) { // 如果下一个字符是-,则解析下一个因子并取其相反数
  117.                     return -parseFactor();
  118.                 }
  119.                 double x;
  120.                 int startPos = this.pos;
  121.                 if (eat('(')) { // 如果下一个字符是(,则解析表达式并跳过)
  122.                     x = parseExpression();
  123.                     eat(')');
  124.                 } else if ((ch >= '0' && ch <= '9') || ch == '.') { // 如果下一个字符是数字或者小数点
  125.                     while ((ch >= '0' && ch <= '9') || ch == '.') { // 解析连续的数字和小数点
  126.                         nextChar();
  127.                     }
  128.                     x = Double.parseDouble(str.substring(startPos, this.pos)); // 将解析出的字符串转换为double类型
  129.                 } else {
  130.                     throw new RuntimeException("意外字符: " + (char) ch); // 非法字符,抛出异常
  131.                 }
  132.                 return x;
  133.             }
  134.         }.parse();
  135.     }

  136.     public static void main(String[] args) {
  137.         new Calculator();
  138.     }
  139. }
复制代码


这个程序创建了一个简单的Swing图形化计算器。它包含一个文本框用于显示输入和结果,以及数字按钮、操作符按钮、等于按钮和清除按钮。用户可以通过点击按钮输入数字和操作符,然后通过点击等于按钮来计算结果。其中的eval函数实现了一个简单的表达式求值算法。

希望这个例子可以帮助你理解如何用Java Swing开发一个简单的图形化计算器!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:22:56 | 显示全部楼层

@FishC1对该代码进行修改使按钮大小不变文本框与清除键单独在第一行,剩下的键位以四行四列排列在文本框与清除键下边
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;

  5. // 计算器类,继承自JFrame,并实现ActionListener接口
  6. class Calculator extends JFrame implements ActionListener {
  7.     private JTextField textField; // 文本框,用于显示表达式和结果
  8.     private JButton[] numberButtons; // 数字按钮数组
  9.     private JButton[] operatorButtons; // 运算符按钮数组
  10.     private JButton equalButton; // 等号按钮
  11.     private JButton clearButton; // 清除按钮
  12.     private String display = ""; // 用于存储当前显示的内容

  13.     // 构造方法
  14.     public Calculator() {
  15.         setTitle("简单计算器"); // 设置窗口标题
  16.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭操作
  17.         setSize(300, 400); // 设置窗口大小
  18.         setLocationRelativeTo(null); // 设置窗口居中显示

  19.         textField = new JTextField(); // 初始化文本框
  20.         textField.setPreferredSize(new Dimension(300, 50)); // 设置文本框大小
  21.         textField.setHorizontalAlignment(JTextField.RIGHT); // 设置文本框文本右对齐

  22.         numberButtons = new JButton[10]; // 初始化数字按钮数组
  23.         for (int i = 0; i < 10; i++) {
  24.             numberButtons[i] = new JButton(String.valueOf(i)); // 创建数字按钮并添加事件监听
  25.             numberButtons[i].addActionListener(this);
  26.         }

  27.         operatorButtons = new JButton[4]; // 初始化运算符按钮数组
  28.         operatorButtons[0] = new JButton("+");
  29.         operatorButtons[1] = new JButton("-");
  30.         operatorButtons[2] = new JButton("*");
  31.         operatorButtons[3] = new JButton("/");
  32.         for (JButton button : operatorButtons) {
  33.             button.addActionListener(this);
  34.         }

  35.         equalButton = new JButton("="); // 初始化等号按钮
  36.         equalButton.addActionListener(this);

  37.         clearButton = new JButton("C"); // 初始化清除按钮
  38.         clearButton.addActionListener(this);

  39.         setLayout(new GridLayout(4, 4)); // 设置布局为4行4列的网格布局
  40.         add(textField); // 添加文本框到界面

  41. // 添加清除按钮到界面,并设置为占据一整行
  42.         add(clearButton);
  43.         clearButton.setPreferredSize(new Dimension(300, 50)); // 设置清除按钮大小
  44.         add(new JPanel()); // 添加一个空白面板,使清除按钮居中显示

  45. // 添加数字按钮到界面
  46.         for (JButton button : numberButtons) {
  47.             add(button);
  48.         }

  49. // 添加运算符按钮到界面
  50.         for (JButton button : operatorButtons) {
  51.             add(button);
  52.         }

  53.         add(equalButton); // 添加等号按钮到界面


  54.         setVisible(true); // 设置界面可见
  55.     }

  56.     // 处理按钮点击事件
  57.     @Override
  58.     public void actionPerformed(ActionEvent e) {
  59.         if (e.getSource() == clearButton) {
  60.             display = ""; // 清空显示内容
  61.         } else if (e.getSource() == equalButton) {
  62.             try {
  63.                 display = String.valueOf(eval(display)); // 计算表达式并显示结果
  64.             } catch (ArithmeticException ex) {
  65.                 display = "错误"; // 若出现异常,显示错误信息
  66.             }
  67.         } else {
  68.             display += ((JButton) e.getSource()).getText(); // 更新显示内容
  69.         }

  70.         textField.setText(display); // 更新文本框显示内容
  71.     }

  72.     // 计算表达式的方法
  73.     public static double eval(final String str) {
  74.         return new Object() {
  75.             int pos = -1, ch;

  76.             void nextChar() {
  77.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  78.             }

  79.             boolean eat(int charToEat) {
  80.                 while (ch == ' ') {
  81.                     nextChar();
  82.                 }
  83.                 if (ch == charToEat) {
  84.                     nextChar();
  85.                     return true;
  86.                 }
  87.                 return false;
  88.             }

  89.             double parse() {
  90.                 nextChar();
  91.                 double x = parseExpression();
  92.                 if (pos < str.length()) {
  93.                     throw new RuntimeException("意外字符: " + (char) ch);
  94.                 }
  95.                 return x;
  96.             }

  97.             double parseExpression() {
  98.                 double x = parseTerm();
  99.                 for (; ; ) {
  100.                     if (eat('+')) {
  101.                         x += parseTerm();
  102.                     } else if (eat('-')) {
  103.                         x -= parseTerm();
  104.                     } else {
  105.                         return x;
  106.                     }
  107.                 }
  108.             }

  109.             double parseTerm() {
  110.                 double x = parseFactor();
  111.                 for (; ; ) {
  112.                     if (eat('*')) {
  113.                         x *= parseFactor();
  114.                     } else if (eat('/')) {
  115.                         x /= parseFactor();
  116.                     } else {
  117.                         return x;
  118.                     }
  119.                 }
  120.             }

  121.             double parseFactor() {
  122.                 if (eat('+')) {
  123.                     return parseFactor();
  124.                 }
  125.                 if (eat('-')) {
  126.                     return -parseFactor();
  127.                 }

  128.                 double x;
  129.                 int startPos = this.pos;
  130.                 if (eat('(')) {
  131.                     x = parseExpression();
  132.                     eat(')');
  133.                 } else if ((ch >= '0' && ch <= '9') || ch == '.') {
  134.                     while ((ch >= '0' && ch <= '9') || ch == '.') {
  135.                         nextChar();
  136.                     }
  137.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  138.                 } else {
  139.                     throw new RuntimeException("意外字符: " + (char) ch);
  140.                 }

  141.                 return x;
  142.             }
  143.         }.parse();
  144.     }

  145.     // 主方法
  146.     public static void main(String[] args) {
  147.         SwingUtilities.invokeLater(new Runnable() {
  148.             public void run() {
  149.                 new Calculator(); // 创建计算器实例
  150.             }
  151.         });
  152.     }
  153. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:23:33 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:22
@FishC1对该代码进行修改使按钮大小不变文本框与清除 ...


修改后的代码,按钮大小不变,文本框和清除键单独在第一行,剩下的键位以四行四列排列在文本框和清除键下边:

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;

  5. class Calculator extends JFrame implements ActionListener {
  6.     private JTextField textField;
  7.     private JButton[] numberButtons;
  8.     private JButton[] operatorButtons;
  9.     private JButton equalButton;
  10.     private JButton clearButton;
  11.     private String display = "";

  12.     public Calculator() {
  13.         setTitle("简单计算器");
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         setSize(300, 400);
  16.         setLocationRelativeTo(null);

  17.         textField = new JTextField();
  18.         textField.setPreferredSize(new Dimension(300, 50));
  19.         textField.setHorizontalAlignment(JTextField.RIGHT);

  20.         numberButtons = new JButton[10];
  21.         for (int i = 0; i < 10; i++) {
  22.             numberButtons[i] = new JButton(String.valueOf(i));
  23.             numberButtons[i].addActionListener(this);
  24.         }

  25.         operatorButtons = new JButton[4];
  26.         operatorButtons[0] = new JButton("+");
  27.         operatorButtons[1] = new JButton("-");
  28.         operatorButtons[2] = new JButton("*");
  29.         operatorButtons[3] = new JButton("/");
  30.         for (JButton button : operatorButtons) {
  31.             button.addActionListener(this);
  32.         }

  33.         equalButton = new JButton("=");
  34.         equalButton.addActionListener(this);

  35.         clearButton = new JButton("C");
  36.         clearButton.addActionListener(this);

  37.         setLayout(new GridLayout(5, 4));
  38.         add(textField);
  39.         add(clearButton);
  40.         clearButton.setPreferredSize(new Dimension(200, 50));
  41.         add(new JPanel());

  42.         for (int i = 7; i <= 9; i++) {
  43.             add(numberButtons[i]);
  44.         }
  45.         add(operatorButtons[0]);

  46.         for (int i = 4; i <= 6; i++) {
  47.             add(numberButtons[i]);
  48.         }
  49.         add(operatorButtons[1]);

  50.         for (int i = 1; i <= 3; i++) {
  51.             add(numberButtons[i]);
  52.         }
  53.         add(operatorButtons[2]);

  54.         add(numberButtons[0]);
  55.         add(operatorButtons[3]);
  56.         add(equalButton);

  57.         setVisible(true);
  58.     }

  59.     @Override
  60.     public void actionPerformed(ActionEvent e) {
  61.         if (e.getSource() == clearButton) {
  62.             display = "";
  63.         } else if (e.getSource() == equalButton) {
  64.             try {
  65.                 display = String.valueOf(eval(display));
  66.             } catch (ArithmeticException ex) {
  67.                 display = "错误";
  68.             }
  69.         } else {
  70.             display += ((JButton) e.getSource()).getText();
  71.         }

  72.         textField.setText(display);
  73.     }

  74.     public static double eval(final String str) {
  75.         return new Object() {
  76.             int pos = -1, ch;

  77.             void nextChar() {
  78.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  79.             }

  80.             boolean eat(int charToEat) {
  81.                 while (ch == ' ') {
  82.                     nextChar();
  83.                 }
  84.                 if (ch == charToEat) {
  85.                     nextChar();
  86.                     return true;
  87.                 }
  88.                 return false;
  89.             }

  90.             double parse() {
  91.                 nextChar();
  92.                 double x = parseExpression();
  93.                 if (pos < str.length()) {
  94.                     throw new RuntimeException("意外字符: " + (char) ch);
  95.                 }
  96.                 return x;
  97.             }

  98.             double parseExpression() {
  99.                 double x = parseTerm();
  100.                 for (; ; ) {
  101.                     if (eat('+')) {
  102.                         x += parseTerm();
  103.                     } else if (eat('-')) {
  104.                         x -= parseTerm();
  105.                     } else {
  106.                         return x;
  107.                     }
  108.                 }
  109.             }

  110.             double parseTerm() {
  111.                 double x = parseFactor();
  112.                 for (; ; ) {
  113.                     if (eat('*')) {
  114.                         x *= parseFactor();
  115.                     } else if (eat('/')) {
  116.                         x /= parseFactor();
  117.                     } else {
  118.                         return x;
  119.                     }
  120.                 }
  121.             }

  122.             double parseFactor() {
  123.                 if (eat('+')) {
  124.                     return parseFactor();
  125.                 }
  126.                 if (eat('-')) {
  127.                     return -parseFactor();
  128.                 }
  129.                 double x;
  130.                 int startPos = this.pos;
  131.                 if (eat('(')) {
  132.                     x = parseExpression();
  133.                     eat(')');
  134.                 } else if (ch >= '0' && ch <= '9') {
  135.                     while (ch >= '0' && ch <= '9') {
  136.                         nextChar();
  137.                     }
  138.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  139.                 } else {
  140.                     throw new RuntimeException("意外字符: " + (char) ch);
  141.                 }
  142.                 return x;
  143.             }
  144.         }.parse();
  145.     }

  146.     public static void main(String[] args) {
  147.         new Calculator();
  148.     }
  149. }
复制代码


现在按钮大小保持不变,文本框和清除键单独在第一行,剩下的键位以四行四列排列在文本框和清除键下方。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:31:23 | 显示全部楼层
@FishC1对该代码进行修改使按钮大小不变加入小数点键,文本框大小变为按钮的三倍与清除键单独在第一行,剩下的键位以四行四列排列在文本框与清除键下边
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:32:02 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:31
@FishC1对该代码进行修改使按钮大小不变加入小数点键 ...


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// 计算器类,继承自JFrame,并实现ActionListener接口
class Calculator extends JFrame implements ActionListener {
    private JTextField textField; // 文本框,用于显示表达式和结果
    private JButton numberButtons; // 数字按钮数组
    private JButton operatorButtons; // 运算符按钮数组
    private JButton equalButton; // 等号按钮
    private JButton clearButton; // 清除按钮
    private String display = ""; // 用于存储当前显示的内容

    // 构造方法
    public Calculator() {
        setTitle("简单计算器"); // 设置窗口标题
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭操作
        setSize(300, 400); // 设置窗口大小
        setLocationRelativeTo(null); // 设置窗口居中显示

        textField = new JTextField(); // 初始化文本框
        textField.setPreferredSize(new Dimension(300, 50)); // 设置文本框大小
        textField.setHorizontalAlignment(JTextField.RIGHT); // 设置文本框文本右对齐

        numberButtons = new JButton[11]; // 初始化数字按钮数组
        for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i)); // 创建数字按钮并添加事件监听
            numberButtons.addActionListener(this);
        }
        numberButtons[10] = new JButton("."); // 创建小数点按钮
        numberButtons[10].addActionListener(this);

        operatorButtons = new JButton[4]; // 初始化运算符按钮数组
        operatorButtons[0] = new JButton("+");
        operatorButtons[1] = new JButton("-");
        operatorButtons[2] = new JButton("*");
        operatorButtons[3] = new JButton("/");
        for (JButton button : operatorButtons) {
            button.addActionListener(this);
        }

        equalButton = new JButton("="); // 初始化等号按钮
        equalButton.addActionListener(this);

        clearButton = new JButton("C"); // 初始化清除按钮
        clearButton.addActionListener(this);

        setLayout(new GridLayout(5, 4)); // 设置布局为5行4列的网格布局

        add(textField); // 添加文本框到界面
        textField.setPreferredSize(new Dimension(300, 150)); // 修改文本框大小,为按钮的3倍

        add(clearButton); // 添加清除按钮到界面,并设置为占据一整行
        clearButton.setPreferredSize(new Dimension(300, 50)); // 设置清除按钮大小

        add(new JPanel()); // 添加一个空白面板,使清除按钮居中显示

        // 添加数字按钮到界面
        for (JButton button : numberButtons) {
            add(button);
        }

        // 添加运算符按钮到界面
        for (JButton button : operatorButtons) {
            add(button);
        }

        add(equalButton); // 添加等号按钮到界面

        setVisible(true); // 设置界面可见
    }

    // 处理按钮点击事件
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clearButton) {
            display = ""; // 清空显示内容
        } else if (e.getSource() == equalButton) {
            try {
                display = String.valueOf(eval(display)); // 计算表达式并显示结果
            } catch (ArithmeticException ex) {
                display = "错误"; // 若出现异常,显示错误信息
            }
        } else {
            display += ((JButton) e.getSource()).getText(); // 更新显示内容
        }
        textField.setText(display); // 更新文本框显示内容
    }

    // 计算表达式的方法
    public static double eval(final String str) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < str.length()) ? str.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') {
                    nextChar();
                }
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < str.length()) {
                    throw new RuntimeException("意外字符: " + (char) ch);
                }
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (; ; ) {
                    if (eat('+')) {
                        x += parseTerm();
                    } else if (eat('-')) {
                        x -= parseTerm();
                    } else {
                        return x;
                    }
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (; ; ) {
                    if (eat('*')) {
                        x *= parseFactor();
                    } else if (eat('/')) {
                        x /= parseFactor();
                    } else {
                        return x;
                    }
                }
            }

            double parseFactor() {
                if (eat('+')) {
                    return parseFactor();
                }
                if (eat('-')) {
                    return -parseFactor();
                }
                double x;
                int startPos = this.pos;
                if (eat('(')) {
                    x = parseExpression();
                    eat(')');
                } else if ((ch >= '0' && ch <= '9') || ch == '.') {
                    while ((ch >= '0' && ch <= '9') || ch == '.') {
                        nextChar();
                    }
                    x = Double.parseDouble(str.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("意外字符: " + (char) ch);
                }
                return x;
            }
        }.parse();
    }

    // 测试
    public static void main(String[] args) {
        new Calculator();
    }
}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:33:40 | 显示全部楼层
@FishC1对该代码进行修改使按钮大小不变加入小数点键,文本框大小变为按钮的三倍与清除键单独在第一行,剩下的键位以四行四列排列在文本框与清除键下边
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;

  5. class Calculator extends JFrame implements ActionListener {
  6.     private JTextField textField;
  7.     private JButton[] numberButtons;
  8.     private JButton[] operatorButtons;
  9.     private JButton equalButton;
  10.     private JButton clearButton;
  11.     private String display = "";

  12.     public Calculator() {
  13.         setTitle("简单计算器");
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.         setSize(400, 400);
  16.         setLocationRelativeTo(null);

  17.         textField = new JTextField();
  18.         textField.setPreferredSize(new Dimension(300, 50)); // 修改文本框长度为键位长度的三倍
  19.         textField.setHorizontalAlignment(JTextField.RIGHT);

  20.         numberButtons = new JButton[10];
  21.         for (int i = 0; i < 10; i++) {
  22.             numberButtons[i] = new JButton(String.valueOf(i));
  23.             numberButtons[i].addActionListener(this);
  24.         }

  25.         operatorButtons = new JButton[4];
  26.         operatorButtons[0] = new JButton("+");
  27.         operatorButtons[1] = new JButton("-");
  28.         operatorButtons[2] = new JButton("*");
  29.         operatorButtons[3] = new JButton("/");
  30.         for (JButton button : operatorButtons) {
  31.             button.addActionListener(this);
  32.         }

  33.         equalButton = new JButton("=");
  34.         equalButton.addActionListener(this);

  35.         clearButton = new JButton("C");
  36.         clearButton.addActionListener(this);

  37.         setLayout(new GridLayout(5, 4));
  38.         add(textField);
  39.         add(clearButton);
  40.         clearButton.setPreferredSize(new Dimension(50, 50));
  41.         add(new JPanel());

  42.         for (int i = 7; i <= 9; i++) {
  43.             add(numberButtons[i]);
  44.         }
  45.         add(operatorButtons[0]);

  46.         for (int i = 4; i <= 6; i++) {
  47.             add(numberButtons[i]);
  48.         }
  49.         add(operatorButtons[1]);

  50.         for (int i = 1; i <= 3; i++) {
  51.             add(numberButtons[i]);
  52.         }
  53.         add(operatorButtons[2]);

  54.         add(numberButtons[0]);
  55.         add(operatorButtons[3]);
  56.         add(equalButton);

  57.         setVisible(true);
  58.     }

  59.     @Override
  60.     public void actionPerformed(ActionEvent e) {
  61.         if (e.getSource() == clearButton) {
  62.             display = "";
  63.         } else if (e.getSource() == equalButton) {
  64.             try {
  65.                 display = String.valueOf(eval(display));
  66.             } catch (ArithmeticException ex) {
  67.                 display = "错误";
  68.             }
  69.         } else {
  70.             display += ((JButton) e.getSource()).getText();
  71.         }

  72.         textField.setText(display);
  73.     }

  74.     public static double eval(final String str) {
  75.         return new Object() {
  76.             int pos = -1, ch;

  77.             void nextChar() {
  78.                 ch = (++pos < str.length()) ? str.charAt(pos) : -1;
  79.             }

  80.             boolean eat(int charToEat) {
  81.                 while (ch == ' ') {
  82.                     nextChar();
  83.                 }
  84.                 if (ch == charToEat) {
  85.                     nextChar();
  86.                     return true;
  87.                 }
  88.                 return false;
  89.             }

  90.             double parse() {
  91.                 nextChar();
  92.                 double x = parseExpression();
  93.                 if (pos < str.length()) {
  94.                     throw new RuntimeException("意外字符: " + (char) ch);
  95.                 }
  96.                 return x;
  97.             }

  98.             double parseExpression() {
  99.                 double x = parseTerm();
  100.                 for (; ; ) {
  101.                     if (eat('+')) {
  102.                         x += parseTerm();
  103.                     } else if (eat('-')) {
  104.                         x -= parseTerm();
  105.                     } else {
  106.                         return x;
  107.                     }
  108.                 }
  109.             }

  110.             double parseTerm() {
  111.                 double x = parseFactor();
  112.                 for (; ; ) {
  113.                     if (eat('*')) {
  114.                         x *= parseFactor();
  115.                     } else if (eat('/')) {
  116.                         x /= parseFactor();
  117.                     } else {
  118.                         return x;
  119.                     }
  120.                 }
  121.             }

  122.             double parseFactor() {
  123.                 if (eat('+')) {
  124.                     return parseFactor();
  125.                 }
  126.                 if (eat('-')) {
  127.                     return -parseFactor();
  128.                 }
  129.                 double x;
  130.                 int startPos = this.pos;
  131.                 if (eat('(')) {
  132.                     x = parseExpression();
  133.                     eat(')');
  134.                 } else if (ch >= '0' && ch <= '9') {
  135.                     while (ch >= '0' && ch <= '9') {
  136.                         nextChar();
  137.                     }
  138.                     x = Double.parseDouble(str.substring(startPos, this.pos));
  139.                 } else {
  140.                     throw new RuntimeException("意外字符: " + (char) ch);
  141.                 }
  142.                 return x;
  143.             }
  144.         }.parse();
  145.     }

  146.     public static void main(String[] args) {
  147.         new Calculator();
  148.     }
  149. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:34:15 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:33
@FishC1对该代码进行修改使按钮大小不变加入小数点键 ...


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends JFrame implements ActionListener {
    private JTextField textField;
    private JButton[] numberButtons;
    private JButton[] operatorButtons;
    private JButton decimalButton;
    private JButton equalButton;
    private JButton clearButton;
    private String display = "";

    public Calculator() {
        setTitle("简单计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500); // 修改窗口高度为500
        setLocationRelativeTo(null);

        textField = new JTextField();
        textField.setPreferredSize(new Dimension(300, 150)); // 修改文本框长度为按钮宽度的三倍
        textField.setHorizontalAlignment(JTextField.RIGHT);

        numberButtons = new JButton[10];
        for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
        }

        operatorButtons = new JButton[4];
        operatorButtons[0] = new JButton("+");
        operatorButtons[1] = new JButton("-");
        operatorButtons[2] = new JButton("*");
        operatorButtons[3] = new JButton("/");
        for (JButton button : operatorButtons) {
            button.addActionListener(this);
        }

        decimalButton = new JButton(".");
        decimalButton.addActionListener(this);

        equalButton = new JButton("=");
        equalButton.addActionListener(this);

        clearButton = new JButton("C");
        clearButton.addActionListener(this);

        setLayout(new GridLayout(6, 4)); // 修改布局为6行4列
        add(textField);
        add(clearButton);
        clearButton.setPreferredSize(new Dimension(100, 50)); // 修改清除按钮宽度
        add(decimalButton);

        for (int i = 7; i <= 9; i++) {
            add(numberButtons);
        }
        add(operatorButtons[0]);

        for (int i = 4; i <= 6; i++) {
            add(numberButtons);
        }
        add(operatorButtons[1]);

        for (int i = 1; i <= 3; i++) {
            add(numberButtons);
        }
        add(operatorButtons[2]);

        add(numberButtons[0]);
        add(equalButton);
        add(operatorButtons[3]);

        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clearButton) {
            display = "";
        } else if (e.getSource() == equalButton) {
            try {
                display = String.valueOf(eval(display));
            } catch (ArithmeticException ex) {
                display = "错误";
            }
        } else {
            display += ((JButton) e.getSource()).getText();
        }
        textField.setText(display);
    }

    public static double eval(final String str) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < str.length()) ? str.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') {
                    nextChar();
                }
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < str.length()) {
                    throw new RuntimeException("意外字符: " + (char) ch);
                }
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (; ; ) {
                    if (eat('+')) {
                        x += parseTerm();
                    } else if (eat('-')) {
                        x -= parseTerm();
                    } else {
                        return x;
                    }
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (; ; ) {
                    if (eat('*')) {
                        x *= parseFactor();
                    } else if (eat('/')) {
                        x /= parseFactor();
                    } else {
                        return x;
                    }
                }
            }

            double parseFactor() {
                if (eat('+')) {
                    return parseFactor();
                }
                if (eat('-')) {
                    return -parseFactor();
                }
                double x;
                int startPos = this.pos;
                if (eat('(')) {
                    x = parseExpression();
                    eat(')');
                } else if ((ch >= '0' && ch <= '9') || ch == '.') { // 添加小数点判断
                    while ((ch >= '0' && ch <= '9') || ch == '.') {
                        nextChar();
                    }
                    x = Double.parseDouble(str.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("意外字符: " + (char) ch);
                }
                return x;
            }
        }.parse();
    }
}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 14:38:48 | 显示全部楼层
@FishC1利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器,有+,-,*,/,.和清除键,且文本框和清除键在第一行,其他的在下方以4*4分布
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 14:39:19 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 14:38
@FishC1利用Java Swing 图形组件开发一个可以进行简单 ...


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {
    private JTextField textField;
    private JButton[] numberButtons;
    private JButton[] operatorButtons;
    private JButton equalButton;
    private JButton clearButton;
    private String display = "";

    public Calculator() {
        setTitle("简单计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);

        // 创建文本框和清除键
        textField = new JTextField();
        textField.setPreferredSize(new Dimension(300, 50));
        textField.setHorizontalAlignment(JTextField.RIGHT);

        clearButton = new JButton("C");
        clearButton.addActionListener(this);

        // 创建数字键按钮
        numberButtons = new JButton[10];
        for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
        }

        // 创建运算符按钮
        operatorButtons = new JButton[4];
        operatorButtons[0] = new JButton("+");
        operatorButtons[1] = new JButton("-");
        operatorButtons[2] = new JButton("*");
        operatorButtons[3] = new JButton("/");
        for (int i = 0; i < 4; i++) {
            operatorButtons.addActionListener(this);
        }

        // 创建等号按钮
        equalButton = new JButton("=");
        equalButton.addActionListener(this);

        // 设置布局为网格布局,5行4列
        setLayout(new GridLayout(5, 4));
        add(textField);
        add(clearButton);
        add(new JPanel());
        
        // 添加数字按钮
        for (int i = 7; i <= 9; i++) {
            add(numberButtons);
        }
        add(operatorButtons[0]); // +
        
        for (int i = 4; i <= 6; i++) {
            add(numberButtons);
        }
        add(operatorButtons[1]); // -
        
        for (int i = 1; i <= 3; i++) {
            add(numberButtons);
        }
        add(operatorButtons[2]); // *
        
        add(numberButtons[0]);
        add(operatorButtons[3]); // /
        add(new JButton("."));
        add(equalButton);

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        JButton source = (JButton) e.getSource();
        if (source == clearButton) { // 清除键
            display = "";
        } else if (source == equalButton) { // 等号键
            display = evaluate(display);
        } else { // 数字键或运算符键
            display += source.getText();
        }
        textField.setText(display);
    }

    private String evaluate(String expression) {
        try {
            return String.valueOf(eval(expression));
        } catch (Exception e) {
            return "Error";
        }
    }

    private double eval(String expression) {
        return new Object() {
            int pos = -1, ch;

            void nextChar() {
                ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
            }

            boolean eat(int charToEat) {
                while (ch == ' ') nextChar();
                if (ch == charToEat) {
                    nextChar();
                    return true;
                }
                return false;
            }

            double parse() {
                nextChar();
                double x = parseExpression();
                if (pos < expression.length()) throw new RuntimeException("Unexpected: " + (char) ch);
                return x;
            }

            double parseExpression() {
                double x = parseTerm();
                for (;;) {
                    if (eat('+')) x += parseTerm();
                    else if (eat('-')) x -= parseTerm();
                    else return x;
                }
            }

            double parseTerm() {
                double x = parseFactor();
                for (;;) {
                    if (eat('*')) x *= parseFactor();
                    else if (eat('/')) x /= parseFactor();
                    else return x;
                }
            }

            double parseFactor() {
                if (eat('+')) return parseFactor();
                if (eat('-')) return -parseFactor();

                double x;
                int startPos = this.pos;
                if (eat('(')) {
                    x = parseExpression();
                    eat(')');
                } else if ((ch >= '0' && ch <= '9') || ch == '.') {
                    while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
                    x = Double.parseDouble(expression.substring(startPos, this.pos));
                } else {
                    throw new RuntimeException("Unexpected: " + (char) ch);
                }

                if (eat('^')) x = Math.pow(x, parseFactor());

                return x;
            }
        }.parse();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator();
            }
        });
    }
}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 15:03:57 | 显示全部楼层
@FishC1通过该代码对你所书写代码进行优化
  1. import javax.script.ScriptEngine;
  2. import javax.script.ScriptEngineManager;
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;


  7. class Calculator extends JFrame{

  8.     //定义JTextField 显示的字符串
  9.     String string = new String();

  10.     public Calculator(){
  11.         // 创建一个 Container 容器并初始化。
  12.         Container container=getContentPane();
  13.         //设置容器布局:网格布局样式,5行1列,水平间距50,垂直间距10
  14.         container.setLayout(new GridLayout(5,1,50,10));
  15.         // 创建一个 JTextField 对象并初始化。 JTextField 是用于显示操作和计算结果的文本框。
  16.         // 参数 26 表明可以显示 26 列的文本内容
  17.         JTextField result_TextField = new JTextField(26);
  18.         //把字符串赋值给文本框
  19.         result_TextField.setText(string);
  20.         //创建一个带文本的按钮-->清除键
  21.         JButton clear_Button = new JButton("    clear     ");
  22.         //给按钮添加事件监听器
  23.         clear_Button.addActionListener(clearButtonListener(result_TextField));
  24.         //数字键0到9
  25.         JButton button0 = new JButton("0");
  26.         button0.addActionListener(numbersAndOperatorsListener(result_TextField));
  27.         JButton button1 = new JButton("1");
  28.         button1.addActionListener(numbersAndOperatorsListener(result_TextField));
  29.         JButton button2 = new JButton("2");
  30.         button2.addActionListener(numbersAndOperatorsListener(result_TextField));
  31.         JButton button3 = new JButton("3");
  32.         button3.addActionListener(numbersAndOperatorsListener(result_TextField));
  33.         JButton button4 = new JButton("4");
  34.         button4.addActionListener(numbersAndOperatorsListener(result_TextField));
  35.         JButton button5 = new JButton("5");
  36.         button5.addActionListener(numbersAndOperatorsListener(result_TextField));
  37.         JButton button6 = new JButton("6");
  38.         button6.addActionListener(numbersAndOperatorsListener(result_TextField));
  39.         JButton button7 = new JButton("7");
  40.         button7.addActionListener(numbersAndOperatorsListener(result_TextField));
  41.         JButton button8 = new JButton("8");
  42.         button8.addActionListener(numbersAndOperatorsListener(result_TextField));
  43.         JButton button9 = new JButton("9");
  44.         button9.addActionListener(numbersAndOperatorsListener(result_TextField));
  45.         //计算命令按钮 加减乘除以及小数点等
  46.         //小数点
  47.         JButton button_spot = new JButton(".");
  48.         button_spot.addActionListener(numbersAndOperatorsListener(result_TextField));
  49.         //加
  50.         JButton button_add = new JButton("+");
  51.         button_add.addActionListener(numbersAndOperatorsListener(result_TextField));
  52.         //减
  53.         JButton button_subtract = new JButton("-");
  54.         button_subtract.addActionListener(numbersAndOperatorsListener(result_TextField));
  55.         //乘
  56.         JButton button_multiply = new JButton("*");
  57.         button_multiply.addActionListener(numbersAndOperatorsListener(result_TextField));
  58.         //除
  59.         JButton button_divide = new JButton("/");
  60.         button_divide.addActionListener(numbersAndOperatorsListener(result_TextField));
  61.         //等于
  62.         JButton button_equal = new JButton("=");
  63.         button_equal.addActionListener(equalButtonListener(result_TextField));
  64.         //创建JPanel面板组件并且采用 BorderLayout布局格式
  65.         JPanel panel = new JPanel(new BorderLayout());
  66.         //在面板中添加文本框组件-->靠左
  67.         panel.add(result_TextField,BorderLayout.WEST);
  68.         //在面板中添加文本框组件-->靠右
  69.         panel.add(clear_Button, BorderLayout.EAST);
  70.         JPanel pan1 = new JPanel(new GridLayout(1,4,5,5));
  71.         pan1.add(button7);
  72.         pan1.add(button8);
  73.         pan1.add(button9);
  74.         pan1.add(button_divide);
  75.         JPanel pan2 = new JPanel(new GridLayout(1,4,5,5));
  76.         pan2.add(button4);
  77.         pan2.add(button5);
  78.         pan2.add(button6);
  79.         pan2.add(button_multiply);
  80.         JPanel pan3 = new JPanel(new GridLayout(1,4,5,5));
  81.         pan3.add(button1);
  82.         pan3.add(button2);
  83.         pan3.add(button3);
  84.         pan3.add(button_subtract);
  85.         JPanel pan4 = new JPanel(new GridLayout(1,4,5,5));
  86.         pan4.add(button0);
  87.         pan4.add(button_spot);
  88.         pan4.add(button_equal);
  89.         pan4.add(button_add);
  90.         //在容器上添加面板控件
  91.         container.add(panel);
  92.         container.add(pan1);
  93.         container.add(pan2);
  94.         container.add(pan3);
  95.         container.add(pan4);
  96.         //将容器外部特性实例化
  97.         setTitle(" Calculator ");
  98.         //设窗体的大小     宽和高
  99.         setSize(400,250);
  100.         //设定窗体的可视化
  101.         setVisible(true);
  102.         //设置窗体的关闭方式
  103.         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  104.     }
  105.     //数字和运算符监听事件
  106.     public ActionListener numbersAndOperatorsListener(JTextField result_TextField ){
  107.         return new ActionListener(){
  108.             @Override
  109.             public void actionPerformed(ActionEvent e) {
  110.                 JButton jButton = (JButton) e.getSource();
  111.                 System.out.println("获取事件监听器:"+jButton.getText());
  112.                 string += jButton.getText();
  113.                 result_TextField.setText(string);
  114.             }
  115.         };
  116.     }
  117.     //使用JDK自带的类可以实现执行字符串中的运算公式的功能
  118.     static ScriptEngine javaScriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
  119.     //等于运算
  120.     public ActionListener equalButtonListener(JTextField result_TextField){

  121.         return  new ActionListener() {
  122.             String str =null;
  123.             @Override
  124.             public void actionPerformed(ActionEvent e) {
  125.                 System.out.println("result_TextField -->"+ result_TextField.getText());
  126.                 str = result_TextField.getText();
  127.                 string = equal(str);
  128.                 result_TextField.setText(string);
  129.             }
  130.             public String equal(String str){
  131.                 String result ="";
  132.                 try {
  133.                     System.out.println(javaScriptEngine.eval(str));
  134.                     result = javaScriptEngine.eval(str).toString();
  135.                 } catch (Exception t) {
  136.                 }
  137.                 return result;
  138.             }
  139.         };
  140.     }
  141.     //清除文本框的内容
  142.     public ActionListener clearButtonListener(JTextField result_TextField){
  143.         return  new ActionListener() {
  144.             @Override
  145.             public void actionPerformed(ActionEvent e) {
  146.                 string = "";
  147.                 result_TextField.setText(string);
  148.             }
  149.         };
  150.     }

  151.     public static void main(String[] args) {
  152.         Calculator calculator = new Calculator();
  153.     }

  154. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-4-11 15:04:31 | 显示全部楼层
卷帘红尘亦爱她 发表于 2024-04-11 15:03
@FishC1通过该代码对你所书写代码进行优化import java ...


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends JFrame {
    private String expression = "";

    public Calculator() {
        Container container = getContentPane();
        container.setLayout(new GridLayout(5, 1, 50, 10));

        JTextField resultTextField = new JTextField(26);
        resultTextField.setText(expression);

        JButton clearButton = new JButton("    Clear     ");
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                expression = "";
                resultTextField.setText(expression);
            }
        });

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(resultTextField, BorderLayout.WEST);
        panel.add(clearButton, BorderLayout.EAST);

        JPanel numPanel = new JPanel(new GridLayout(1, 4, 5, 5));
        JPanel operatorPanel = new JPanel(new GridLayout(1, 4, 5, 5));

        ActionListener numAndOperatorListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JButton button = (JButton) e.getSource();
                expression += button.getText();
                resultTextField.setText(expression);
            }
        };

        for (int i = 1; i <= 9; i++) {
            JButton numButton = new JButton(Integer.toString(i));
            numButton.addActionListener(numAndOperatorListener);
            numPanel.add(numButton);
        }

        JButton zeroButton = new JButton("0");
        zeroButton.addActionListener(numAndOperatorListener);
        JButton dotButton = new JButton(".");
        dotButton.addActionListener(numAndOperatorListener);
        JButton equalButton = new JButton("=");
        equalButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
                try {
                    Object result = scriptEngine.eval(expression);
                    expression = result.toString();
                    resultTextField.setText(expression);
                } catch (Exception ex) {
                    expression = "";
                    resultTextField.setText("Error");
                }
            }
        });
        JButton addButton = new JButton("+");
        addButton.addActionListener(numAndOperatorListener);
        JButton subtractButton = new JButton("-");
        subtractButton.addActionListener(numAndOperatorListener);
        JButton multiplyButton = new JButton("*");
        multiplyButton.addActionListener(numAndOperatorListener);
        JButton divideButton = new JButton("/");
        divideButton.addActionListener(numAndOperatorListener);

        operatorPanel.add(zeroButton);
        operatorPanel.add(dotButton);
        operatorPanel.add(equalButton);
        operatorPanel.add(addButton);
        operatorPanel.add(subtractButton);
        operatorPanel.add(multiplyButton);
        operatorPanel.add(divideButton);

        container.add(panel);
        container.add(numPanel);
        container.add(operatorPanel);

        setTitle("Calculator");
        setSize(400, 250);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Calculator());
    }
}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-4-11 15:05:51 | 显示全部楼层
@FishC1对你所写代码进行修改将下方按钮改为四行
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 19:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表