试卷1

作者: 青晨点支烟 | 来源:发表于2023-09-10 10:03 被阅读0次

程序编写和修改

基本计算器应用

你需要开发一个简单的Java桌面计算器应用。这个计算器应该具有以下基本功能:

用户可以输入数字和运算符(+、-、*、/)来执行基本的算术运算。

计算器应该能够显示输入和结果,以便用户可以看到他们的操作。

用户应该能够进行连续运算,例如输入"5 + 3 * 2",并正确计算结果。

应用程序应该包含一个“清除”按钮,以允许用户清除输入并重新开始。

改进计算器应用

在基本计算器应用的基础上,你需要实现以下改进功能:

添加一个小数点按钮,使用户能够输入小数。

添加一个平方根按钮,使用户能够计算输入数字的平方根。

添加一个百分比按钮,使用户能够将当前数字转换为百分比。

实现一个“回退”按钮,允许用户删除他们最后输入的字符。

标准答案:


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class CalculatorApp extends JFrame implements ActionListener {

    private JTextField textField;

    private String input = "";

    public CalculatorApp() {

        // 创建界面和组件

        setTitle("简易计算器");

        setSize(300, 400);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLayout(new BorderLayout());

        textField = new JTextField();

        textField.setFont(new Font("Arial", Font.PLAIN, 24));

        textField.setHorizontalAlignment(JTextField.RIGHT);

        add(textField, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();

        buttonPanel.setLayout(new GridLayout(5, 4));

        // 创建按钮并添加到面板上

        String[] buttonLabels = {

            "7", "8", "9", "/",

            "4", "5", "6", "*",

            "1", "2", "3", "-",

            "0", ".", "=", "+"

        };

        for (String label : buttonLabels) {

            JButton button = new JButton(label);

            button.setFont(new Font("Arial", Font.PLAIN, 18));

            button.addActionListener(this);

            buttonPanel.add(button);

        }

        add(buttonPanel, BorderLayout.CENTER);

        JButton clearButton = new JButton("清除");

        clearButton.setFont(new Font("Arial", Font.PLAIN, 18));

        clearButton.addActionListener(this);

        add(clearButton, BorderLayout.SOUTH);

    }

    @Override

    public void actionPerformed(ActionEvent e) {

        String command = e.getActionCommand();

        if (command.equals("=")) {

            try {

                double result = evaluate(input);

                textField.setText(String.valueOf(result));

            } catch (Exception ex) {

                textField.setText("错误");

            }

            input = "";

        } else if (command.equals("清除")) {

            input = "";

            textField.setText("");

        } else {

            input += command;

            textField.setText(input);

        }

    }

    private double evaluate(String expression) throws Exception {

        // 实现基本计算器逻辑

        // 这里需要你实现计算逻辑

        return 0.0;

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {

            CalculatorApp calculator = new CalculatorApp();

            calculator.setVisible(true);

        });

    }

}

改进程序答案:

改进计算器应用的实现将包括添加小数点、平方根、百分比和回退功能的代码。以下是一个简要的示例:


// 在 CalculatorApp 类中添加以下方法和代码

private boolean isOperator(char c) {

    return c == '+' || c == '-' || c == '*' || c == '/';

}

private double calculate(double operand1, char operator, double operand2) {

    switch (operator) {

        case '+':

            return operand1 + operand2;

        case '-':

            return operand1 - operand2;

        case '*':

            return operand1 * operand2;

        case '/':

            if (operand2 != 0) {

                return operand1 / operand2;

            } else {

                throw new ArithmeticException("除数不能为零");

            }

        default:

            throw new IllegalArgumentException("无效的运算符: " + operator);

    }

}

private double evaluate(String expression) throws Exception {

    // 使用栈来计算表达式

    Stack<Double> operandStack = new Stack<>();

    Stack<Character> operatorStack = new Stack<>();

    int index = 0;

    while (index < expression.length()) {

        char currentChar = expression.charAt(index);

        if (Character.isDigit(currentChar) || currentChar == '.') {

            StringBuilder operandBuilder = new StringBuilder();

            while (index < expression.length() && (Character.isDigit(expression.charAt(index)) || expression.charAt(index) == '.')) {

                operandBuilder.append(expression.charAt(index));

                index++;

            }

            double operand = Double.parseDouble(operandBuilder.toString());

            operandStack.push(operand);

        } else if (isOperator(currentChar)) {

            while (!operatorStack.isEmpty() && isOperator(operatorStack.peek()) && getPrecedence(currentChar) <= getPrecedence(operatorStack.peek())) {

                double operand2 = operandStack.pop();

                double operand1 = operandStack.pop();

                char operator = operatorStack.pop();

                double result = calculate(operand1, operator, operand2);

                operandStack.push(result);

            }

            operatorStack.push(currentChar);

            index++;

        } else if (currentChar == '(') {

            operatorStack.push(currentChar);

            index++;

        } else if (currentChar == ')') {

            while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {

                double operand2 = operandStack.pop();

                double operand1 = operandStack.pop();

                char operator = operatorStack.pop();

                double result = calculate(operand1, operator, operand2);

                operandStack.push(result);

            }

            if (!operatorStack.isEmpty() && operatorStack.peek() == '(') {

                operatorStack.pop();

            } else {

                throw new IllegalArgumentException("括号不匹配");

            }

            index++;

        } else {

            throw new IllegalArgumentException("无效字符: " + currentChar);

        }

    }

    while (!operatorStack.isEmpty()) {

        if (operatorStack.peek() == '(') {

            throw new IllegalArgumentException("括号不匹配");

        }

        double operand2 = operandStack.pop();

        double operand1 = operandStack.pop();

        char operator = operatorStack.pop();

        double result = calculate(operand1, operator, operand2);

        operandStack.push(result);

    }

    if (operandStack.size() == 1 && operatorStack.isEmpty()) {

        return operandStack.pop();

    } else {

        throw new IllegalArgumentException("无效表达式");

    }

}

private int getPrecedence(char operator) {

    if (operator == '+' || operator == '-') {

        return 1;

    } else if (operator == '*' || operator == '/') {

        return 2;

    } else {

        return 0;

    }

}

功能调试

下面是一个简单的学生信息管理系统的Java桌面应用代码,你可以在此基础上进行功能调试与验证。随后,我将提供一个包含五个问题的上机考核题目以及标准答案。


public class Student {

    private String studentNumber;

    private String name;

    private double score;

    public Student(String studentNumber, String name, double score) {

        this.studentNumber = studentNumber;

        this.name = name;

        this.score = score;

    }

    public String getStudentNumber() {

        return studentNumber;

    }

    public String getName() {

        return name;

    }

    public double getScore() {

        return score;

    }

    @Override

    public String toString() {

        return "Student [studentNumber=" + studentNumber + ", name=" + name + ", score=" + score + "]";

    }

}

学生信息管理系统类 (StudentManager.java):


import java.util.ArrayList;

import java.util.List;

public class StudentManager {

    private List<Student> students;

    public StudentManager() {

        students = new ArrayList<>();

    }

    public void addStudent(Student student) {

        students.add(student);

    }

    public void deleteStudentByStudentNumber(String studentNumber) {

        students.removeIf(student -> student.getStudentNumber().equals(studentNumber));

    }

    public List<Student> getAllStudents() {

        return students;

    }

    public void sortStudentsByScore(boolean ascending) {

        students.sort((s1, s2) -> {

            if (ascending) {

                return Double.compare(s1.getScore(), s2.getScore());

            } else {

                return Double.compare(s2.getScore(), s1.getScore());

            }

        });

    }

    public List<Student> searchStudentsByName(String name) {

        List<Student> foundStudents = new ArrayList<>();

        for (Student student : students) {

            if (student.getName().equalsIgnoreCase(name)) {

                foundStudents.add(student);

            }

        }

        return foundStudents;

    }

}

标准答案示例:

验证添加学生信息功能:


Studentstudent=newStudent("S12345","Alice",88.5);

studentManager.addStudent(student);

List allStudents = studentManager.getAllStudents();System.out.println("所有学生信息:"+ allStudents);

验证删除学生信息功能:


studentManager.deleteStudentByStudentNumber("S12345");

List allStudents = studentManager.getAllStudents();

System.out.println("所有学生信息:"+ allStudents);

验证按成绩排序功能:


studentManager.sortStudentsByScore(true);

List sortedStudents = studentManager.getAllStudents();

System.out.println("按成绩升序排序后的学生信息:"+ sortedStudents);

验证按姓名查找功能:


List foundStudents = studentManager.searchStudentsByName("Alice");

System.out.println("查找到的学生信息:"+ foundStudents);

相关文章

  • 试卷分析1

    本次测试是孩子们进入一年级以来第一次测试,我把测试中出现的问题分析给家长朋友们,一起查缺补漏,让我们的孩子们取得更...

  • 测试卷1

  • 期末复习试卷1

    一、填一填。 1、2019年是( )年,这年的第一季度一共有( )天。 2、4平方千米=( ...

  • 10.16作业大军(つД`)ノ

    1.政治试卷 2h 包括复习 2.英语试卷x3 一张1h 3.历史试卷1h

  • 第6天

    最后一天了 物理作业本1.5h 物理试卷1h 化学试卷1h 政治试卷1h 地理作业本30min 地理试卷40min...

  • 压强测试卷1

  • 西经试卷1-4

    名词解释 经济稀缺性:人力资源和非人力资源的数量都是有限的 边际效用递减规律:边际效用递减规律 3. 机会成本:生...

  • 1.试卷风波

    “破瓦横尸绛红杀,炙炎洛雪北风刮。 吟思苍穹有深意,来年血祭彼岸花。” 在萧虎的每一本教材和练习册上,都是白纸红字...

  • 未来可期

    昨天是什么节奏?讲了4份试卷,看了1份科学试卷,1份数学试卷。还找n个同学谈话。写个32个美术字。 下午接完孩子,...

  • 今日内容`

    语文试卷1张读了第八单元所有生字和课文数学考试卷改错写到五道题本上了语文试卷改错数学1课1练68.69页体育和音乐...

网友评论

      本文标题:试卷1

      本文链接:https://www.haomeiwen.com/subject/rrlsvdtx.html