FishC 发表于 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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 13:54:44

@FishC1 利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器。

FishC 发表于 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
            buttonPanel.add(numberButtons);
      }

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 13:56:07

@FishC1通过用java 利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器。

FishC 发表于 2024-4-11 13:56:42

卷帘红尘亦爱她 发表于 2024-04-11 13:56
@FishC1通过用java 利用Java Swing 图形组件开发一个 ...

当然可以!下面是一个简单的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(300, 400);
      setLocationRelativeTo(null);

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

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

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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, 3));
      add(textField);
      for (JButton button : numberButtons) {
            add(button);
      }
      for (JButton button : operatorButtons) {
            add(button);
      }
      add(equalButton);
      add(clearButton);

      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) {
      SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator();
            }
      });
    }
}

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:01:53

@FishC1对每行代码进行注释            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;
            }

FishC 发表于 2024-4-11 14:03:32

卷帘红尘亦爱她 发表于 2024-04-11 14:01
@FishC1对每行代码进行注释            int pos = -1, ...

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

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()方法调用parseExpression()方法来解析整个表达式,parseExpression()方法又调用parseTerm()方法来解析加减法,parseTerm()方法又调用parseFactor()方法来解析乘除法。eat()函数用于检查和吃掉指定的字符。整个过程通过递归和循环来实现对表达式的解析和计算。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:04:25

@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 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
      }

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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, 3));
      add(textField);
      for (JButton button : numberButtons) {
            add(button);
      }
      for (JButton button : operatorButtons) {
            add(button);
      }
      add(equalButton);
      add(clearButton);

      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) {
      SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator();
            }
      });
    }
}

FishC 发表于 2024-4-11 14:05:08

卷帘红尘亦爱她 发表于 2024-04-11 14:04
@FishC1对每行代码进行注释import javax.swing.*;
im ...

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

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 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
      }

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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, 3));
      add(textField);
      for (JButton button : numberButtons) {
            add(button);
      }
      for (JButton button : operatorButtons) {
            add(button);
      }
      add(equalButton);
      add(clearButton);

      setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == clearButton) { // 清除按钮点击事件
            display = "";
      } else if (e.getSource() == equalButton) { // 等于按钮点击事件
            try {
                display = String.valueOf(eval(display)); // 调用eval方法计算表达式结果
            } 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)); // 将解析出的字符串转换为double类型
                } else {
                  throw new RuntimeException("意外字符: " + (char) ch); // 非法字符,抛出异常
                }
                return x;
            }
      }.parse();
    }

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

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:22:56


@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; // 初始化数字按钮数组
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i)); // 创建数字按钮并添加事件监听
            numberButtons.addActionListener(this);
      }

      operatorButtons = new JButton; // 初始化运算符按钮数组
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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(4, 4)); // 设置布局为4行4列的网格布局
      add(textField); // 添加文本框到界面

// 添加清除按钮到界面,并设置为占据一整行
      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) {
      SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator(); // 创建计算器实例
            }
      });
    }
}

FishC 发表于 2024-4-11 14:23:33

卷帘红尘亦爱她 发表于 2024-04-11 14:22
@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 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
      }

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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));
      add(textField);
      add(clearButton);
      clearButton.setPreferredSize(new Dimension(200, 50));
      add(new JPanel());

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

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

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

      add(numberButtons);
      add(operatorButtons);
      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') {
                  while (ch >= '0' && ch <= '9') {
                        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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:31:23

@FishC1对该代码进行修改使按钮大小不变加入小数点键,文本框大小变为按钮的三倍与清除键单独在第一行,剩下的键位以四行四列排列在文本框与清除键下边

FishC 发表于 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; // 初始化数字按钮数组
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i)); // 创建数字按钮并添加事件监听
            numberButtons.addActionListener(this);
      }
      numberButtons = new JButton("."); // 创建小数点按钮
      numberButtons.addActionListener(this);

      operatorButtons = new JButton; // 初始化运算符按钮数组
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:33:40

@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 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);

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

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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));
      add(textField);
      add(clearButton);
      clearButton.setPreferredSize(new Dimension(50, 50));
      add(new JPanel());

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

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

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

      add(numberButtons);
      add(operatorButtons);
      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') {
                  while (ch >= '0' && ch <= '9') {
                        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 发表于 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
      }

      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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);

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

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

      add(numberButtons);
      add(equalButton);
      add(operatorButtons);

      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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 14:38:48

@FishC1利用Java Swing 图形组件开发一个可以进行简单的四则运算的图形化计算器,有+,-,*,/,.和清除键,且文本框和清除键在第一行,其他的在下方以4*4分布

FishC 发表于 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;
      for (int i = 0; i < 10; i++) {
            numberButtons = new JButton(String.valueOf(i));
            numberButtons.addActionListener(this);
      }

      // 创建运算符按钮
      operatorButtons = new JButton;
      operatorButtons = new JButton("+");
      operatorButtons = new JButton("-");
      operatorButtons = new JButton("*");
      operatorButtons = 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); // +
      
      for (int i = 4; i <= 6; i++) {
            add(numberButtons);
      }
      add(operatorButtons); // -
      
      for (int i = 1; i <= 3; i++) {
            add(numberButtons);
      }
      add(operatorButtons); // *
      
      add(numberButtons);
      add(operatorButtons); // /
      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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 15:03:57

@FishC1通过该代码对你所书写代码进行优化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{

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

    public Calculator(){
      // 创建一个 Container 容器并初始化。
      Container container=getContentPane();
      //设置容器布局:网格布局样式,5行1列,水平间距50,垂直间距10
      container.setLayout(new GridLayout(5,1,50,10));
      // 创建一个 JTextField 对象并初始化。 JTextField 是用于显示操作和计算结果的文本框。
      // 参数 26 表明可以显示 26 列的文本内容
      JTextField result_TextField = new JTextField(26);
      //把字符串赋值给文本框
      result_TextField.setText(string);
      //创建一个带文本的按钮-->清除键
      JButton clear_Button = new JButton("    clear   ");
      //给按钮添加事件监听器
      clear_Button.addActionListener(clearButtonListener(result_TextField));
      //数字键0到9
      JButton button0 = new JButton("0");
      button0.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button1 = new JButton("1");
      button1.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button2 = new JButton("2");
      button2.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button3 = new JButton("3");
      button3.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button4 = new JButton("4");
      button4.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button5 = new JButton("5");
      button5.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button6 = new JButton("6");
      button6.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button7 = new JButton("7");
      button7.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button8 = new JButton("8");
      button8.addActionListener(numbersAndOperatorsListener(result_TextField));
      JButton button9 = new JButton("9");
      button9.addActionListener(numbersAndOperatorsListener(result_TextField));
      //计算命令按钮 加减乘除以及小数点等
      //小数点
      JButton button_spot = new JButton(".");
      button_spot.addActionListener(numbersAndOperatorsListener(result_TextField));
      //加
      JButton button_add = new JButton("+");
      button_add.addActionListener(numbersAndOperatorsListener(result_TextField));
      //减
      JButton button_subtract = new JButton("-");
      button_subtract.addActionListener(numbersAndOperatorsListener(result_TextField));
      //乘
      JButton button_multiply = new JButton("*");
      button_multiply.addActionListener(numbersAndOperatorsListener(result_TextField));
      //除
      JButton button_divide = new JButton("/");
      button_divide.addActionListener(numbersAndOperatorsListener(result_TextField));
      //等于
      JButton button_equal = new JButton("=");
      button_equal.addActionListener(equalButtonListener(result_TextField));
      //创建JPanel面板组件并且采用 BorderLayout布局格式
      JPanel panel = new JPanel(new BorderLayout());
      //在面板中添加文本框组件-->靠左
      panel.add(result_TextField,BorderLayout.WEST);
      //在面板中添加文本框组件-->靠右
      panel.add(clear_Button, BorderLayout.EAST);
      JPanel pan1 = new JPanel(new GridLayout(1,4,5,5));
      pan1.add(button7);
      pan1.add(button8);
      pan1.add(button9);
      pan1.add(button_divide);
      JPanel pan2 = new JPanel(new GridLayout(1,4,5,5));
      pan2.add(button4);
      pan2.add(button5);
      pan2.add(button6);
      pan2.add(button_multiply);
      JPanel pan3 = new JPanel(new GridLayout(1,4,5,5));
      pan3.add(button1);
      pan3.add(button2);
      pan3.add(button3);
      pan3.add(button_subtract);
      JPanel pan4 = new JPanel(new GridLayout(1,4,5,5));
      pan4.add(button0);
      pan4.add(button_spot);
      pan4.add(button_equal);
      pan4.add(button_add);
      //在容器上添加面板控件
      container.add(panel);
      container.add(pan1);
      container.add(pan2);
      container.add(pan3);
      container.add(pan4);
      //将容器外部特性实例化
      setTitle(" Calculator ");
      //设窗体的大小   宽和高
      setSize(400,250);
      //设定窗体的可视化
      setVisible(true);
      //设置窗体的关闭方式
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    //数字和运算符监听事件
    public ActionListener numbersAndOperatorsListener(JTextField result_TextField ){
      return new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                JButton jButton = (JButton) e.getSource();
                System.out.println("获取事件监听器:"+jButton.getText());
                string += jButton.getText();
                result_TextField.setText(string);
            }
      };
    }
    //使用JDK自带的类可以实现执行字符串中的运算公式的功能
    static ScriptEngine javaScriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    //等于运算
    public ActionListener equalButtonListener(JTextField result_TextField){

      returnnew ActionListener() {
            String str =null;
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("result_TextField -->"+ result_TextField.getText());
                str = result_TextField.getText();
                string = equal(str);
                result_TextField.setText(string);
            }
            public String equal(String str){
                String result ="";
                try {
                  System.out.println(javaScriptEngine.eval(str));
                  result = javaScriptEngine.eval(str).toString();
                } catch (Exception t) {
                }
                return result;
            }
      };
    }
    //清除文本框的内容
    public ActionListener clearButtonListener(JTextField result_TextField){
      returnnew ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                string = "";
                result_TextField.setText(string);
            }
      };
    }

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

}

FishC 发表于 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 小助理,如未能正确解答您的问题,请继续追问。

卷帘红尘亦爱她 发表于 2024-4-11 15:05:51

@FishC1对你所写代码进行修改将下方按钮改为四行
页: 1 2 3 4 5 6 [7] 8 9 10
查看完整版本: 地图设计