第二次作业

本文介绍了一个使用Java语言实现的简易计算器程序,通过按钮点击事件触发数学运算,支持基本的加减乘除操作。
 

 

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

 

public class JCalculator extends JFrame implements ActionListener {

   

    private static final long serialVersionUID = -169068472193786457L;

   

    private class WindowCloser extends WindowAdapter {

       public void windowClosing(WindowEvent we) {

           System.exit(0);

       }

    }

 

    int i;

    // Strings for Digit & Operator buttons.

    private final String[] str = { "7", "8", "9", "/", "4", "5", "6", "*", "1",

           "2", "3", "-", ".", "0", "=", "+" };

    // Build buttons.

    JButton[] buttons = new JButton[str.length];

    // For cancel or reset.

    JButton reset = new JButton("CE");

    // Build the text field to show the result.

    JTextField display = new JTextField("0");

   

    /**

    * Constructor without parameters.

    */

    public JCalculator() {

       super("Calculator");

       // Add a panel.

       JPanel panel1 = new JPanel(new GridLayout(4, 4));

       // panel1.setLayout(new GridLayout(4,4));

       for (i = 0; i < str.length; i++) {

           buttons[i] = new JButton(str[i]);

           panel1.add(buttons[i]);

       }

       JPanel panel2 = new JPanel(new BorderLayout());

       // panel2.setLayout(new BorderLayout());

       panel2.add("Center", display);

       panel2.add("East", reset);

       // JPanel panel3 = new Panel();

       getContentPane().setLayout(new BorderLayout());

       getContentPane().add("North", panel2);

       getContentPane().add("Center", panel1);

       // Add action listener for each digit & operator button.

       for (i = 0; i < str.length; i++)

           buttons[i].addActionListener(this);

       // Add listener for "reset" button.

       reset.addActionListener(this);

       // Add listener for "display" button.

       display.addActionListener(this);

       // The "close" button "X".

       addWindowListener(new WindowCloser());

       // Initialize the window size.

       setSize(800, 800);

       // Show the window.

       // show(); Using show() while JDK version is below 1.5.

       setVisible(true);

       // Fit the certain size.

       pack();

    }  

   

    public void actionPerformed(ActionEvent e) {

       Object target = e.getSource();

       String label = e.getActionCommand();

       if (target == reset)

           handleReset();

       else if ("0123456789.".indexOf(label) > 0)

           handleNumber(label);

       else

           handleOperator(label);

    }

    // Is the first digit pressed?

    boolean isFirstDigit = true;

    /**

    * Number handling.

    * @param key the key of the button.

    */

    public void handleNumber(String key) {

       if (isFirstDigit)

           display.setText(key);

       else if ((key.equals(".")) && (display.getText().indexOf(".") < 0))

           display.setText(display.getText() + ".");

       else if (!key.equals("."))

           display.setText(display.getText() + key);

       isFirstDigit = false;

    }

   

    /**

    * Reset the calculator.

    */

    public void handleReset() {

       display.setText("0");

       isFirstDigit = true;

       operator = "=";

    }

 

    double number = 0.0;

    String operator = "=";

   

    /**

    * Handling the operation.

    * @param key pressed operator's key.

    */

    public void handleOperator(String key) {

       if (operator.equals("+"))

           number += Double.valueOf(display.getText());

       else if (operator.equals("-"))

           number -= Double.valueOf(display.getText());

       else if (operator.equals("*"))

           number *= Double.valueOf(display.getText());

       else if (operator.equals("/"))

           number /= Double.valueOf(display.getText());

       else if (operator.equals("="))

           number = Double.valueOf(display.getText());

       display.setText(String.valueOf(number));

       operator = key;

       isFirstDigit = true;

    }

   

    public static void main(String[] args) {

       new JCalculator();

    }

}

转载于:https://www.cnblogs.com/xiaojun1009/p/4423154.html

Python 第二次作业中涉及了多个知识点,包括基础的循环结构、数学问题的编程实现,以及函数的应用等。以下是对部分作业内容和解答的详细说明: 1. **斐波那契数列的打印** 作业中有一个题目要求使用 `for` 循环来打印斐波那契数列的前 10 项。初始值为 `a, b = 0, 1`,并且循环执行 10 次,每次打印当前的 `a` 值。正确的代码片段如下: ```python a, b = 0, 1 for _ in range(10): print(a, end=' ') a, b = b, a + b ``` 上述代码中的关键部分是 `a, b = b, a + b`,这一行代码负责更新斐波那契数列的两个相邻值。通过这种方式,可以高效地生成斐波那契数列[^1]。 2. **高次方程求根** 另一个作业题目涉及求解一个五次方程的根。题目提供了一个函数 `f(x)`,其定义为 $ f(x) = x^5 - 15x^4 + 85x^3 - 225x^2 + 274x - 121 $。为了求解该方程在区间 [1.5, 2.4] 内的根,采用了二分法。具体实现如下: ```python def f(x): return x**5 - 15*x**4 + 85*x**3 - 225*x**2 + 274*x - 121 l, r = 1.5, 2.4 k = 0 while k < 20: mid = (l + r) / 2 x = f(mid) if x > 0: l = mid else: r = mid k += 1 print(round(mid, 6)) ``` 在这段代码中,`while` 循环执行了 20 次,每次通过计算中间值 `mid` 来判断根的位置,并逐步缩小搜索范围。最终输出的 `mid` 是近似解,保留了 6 位小数[^2]。 3. **两数之和的查找** 作业还包含了一个经典的算法问题——两数之和。题目要求找到数组中两个数的下标,使得它们的和等于给定的目标值 `target`。该问题可以通过哈希表(字典)来高效解决。具体实现如下: ```python def twoSum(nums, target): dict_ = {} for i in range(len(nums)): m = nums[i] if target - m in dict_: return (dict_[target - m], i) dict_[m] = i nums = [3, 4, 9, 7, 10] target = 11 res = twoSum(nums, target) print(res) ``` 上述代码中,`twoSum` 函数通过遍历数组并使用字典记录已遍历的数值及其下标,从而在后续查找中快速判断是否存在满足条件的配对。最终输出的结果是 `(0, 1)`,表示数组中索引为 0 和 1 的两个数之和等于目标值 11[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值