[Java] 用 Swing 生成一个最大公约数计算器

Swing 生成一个最大公约数计算器

最终的效果如下图所示 ⬇️

我来说说核心的步骤。

第一步:利用欧几里得算法计算最大公约数

欧几里得算法是计算最大公约数的经典算法。如果我们使用 java 中的 BigInteger,那么从理论上讲,可以计算出任意大小的两个整数的最大公约数(按照定义,这两个整数不能同时为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 0 0 </math>0)。

如果用 Swing 来生成用户界面的话,用户的输入会是 String。我们需要写点将 String 转化为 BigInteger 的代码。

有了上述的思路后,可以先把计算最大公约数和 String -> BigInteger 转化的代码写好 ⬇️

java 复制代码
class GCDCalculator {

    /**
     * Extract a number from {@param num} and convert it to a BigInteger
     *
     * @param num given string
     * @return corresponding BigInteger (the original sign will be ignored as it has no impact to GCD)
     */
    private BigInteger standardize(String num) {
        num = num.trim();
        if (num.startsWith("-") || num.startsWith("+")) {
            num = num.substring(1);
        }
        if (num.equals("0")) {
            return BigInteger.ZERO;
        }

        int len = num.length();
        BigInteger result = BigInteger.ZERO;
        for (int i = 0; i < len; i++) {
            int digit = num.charAt(i) - '0';
            if (digit < 0 || digit > 9) {
                throw new IllegalArgumentException("至少一个整数中含有不合法的字符,请检查!");
            }
            result = result.multiply(BigInteger.valueOf(10L)).add(BigInteger.valueOf(digit));
        }
        return result;
    }

    public BigInteger calculateGCD(String a, String b) {
        return calculateGCD(standardize(a), standardize(b));
    }

    public BigInteger calculateGCD(BigInteger a, BigInteger b) {
        if (a.equals(BigInteger.ZERO) && b.equals(BigInteger.ZERO)) {
            throw new IllegalArgumentException("两个整数不能都是0!");
        }
        return doCalculateGCD(a, b);
    }

    private BigInteger doCalculateGCD(BigInteger a, BigInteger b) {
        if (b.equals(BigInteger.ZERO)) {
            return a;
        }
        return doCalculateGCD(b, a.mod(b));
    }

    public static void main(String[] args) {
        GCDCalculator gcdCalculator = new GCDCalculator();
        System.out.println(gcdCalculator.calculateGCD("100", "20")); // should be 20
        System.out.println(gcdCalculator.calculateGCD("10", "12")); // should be 2
        System.out.println(gcdCalculator.calculateGCD("233", "144")); // should be 1
        System.out.println(gcdCalculator.calculateGCD("12345", "67890")); // should be 15
        System.out.println(gcdCalculator.calculateGCD("54321", "9876")); // should be 3
        System.out.println(gcdCalculator.calculateGCD("1160718174", "316258250")); // should be 1078
    }
}

我在 main 方法里写了几个测试用例,计算的结果都符合预期。

第二步:加入和 Swing 相关的代码

既然计算最大公约数的部分已经写好了,那么现在只需要把和 Swing 相关的代码也加上,就可以和用户进行交互了。因为 Swing 的知识点比较零碎,我自己知道得也很粗浅,这一部分就不展开说了。完整的代码如下 (第一步中出现的 main 方法已经删除了) ⬇️

java 复制代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;

public class MyGCDCalculator {
    public static void main(String[] args) {
        EventQueue.invokeLater(new CalcGreatestCommonDivisor());
    }
}

class CalcGreatestCommonDivisor implements Runnable {

    @Override
    public void run() {
        SimpleFrame frame = new SimpleFrame("最大公约数计算器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        JPanel northPanel = new JPanel();
        northPanel.setLayout(new GridLayout(3, 2));
        JTextField textField1 = new JTextField();
        northPanel.add(new JLabel("请输入第一个整数:", SwingConstants.RIGHT));
        northPanel.add(textField1);
        northPanel.add(new JLabel("请输入第二个整数:", SwingConstants.RIGHT));
        JTextField textField2 = new JTextField();
        northPanel.add(textField2);

        northPanel.add(new JLabel("这两个整数的最大公约数是:", SwingConstants.RIGHT));
        JTextField textField3 = new JTextField();
        textField3.setEnabled(false);
        northPanel.add(textField3);

        frame.add(northPanel, BorderLayout.NORTH);
        JButton button = new JButton("计算最大公约数");
        button.addActionListener(new ActionListener() {
            private final GCDCalculator calculator = new GCDCalculator();

            @Override
            public void actionPerformed(ActionEvent e) {
                String a = textField1.getText();
                String b = textField2.getText();
                try {
                    BigInteger gcd = calculator.calculateGCD(a, b);
                    textField3.setText(gcd.toString());
                } catch (IllegalArgumentException exception) {
                    textField3.setText(exception.getMessage());
                }
            }
        });
        frame.add(button, BorderLayout.SOUTH);
    }
}


class SimpleFrame extends JFrame {
    public SimpleFrame(String title) {
        setTitle(title);
        setSize(600, 200);
    }
}

class GCDCalculator {

    /**
     * Extract a number from {@param num} and convert it to a BigInteger
     *
     * @param num given string
     * @return corresponding BigInteger (the original sign will be ignored as it has no impact to GCD)
     */
    private BigInteger standardize(String num) {
        num = num.trim();
        if (num.startsWith("-") || num.startsWith("+")) {
            num = num.substring(1);
        }
        if (num.equals("0")) {
            return BigInteger.ZERO;
        }

        int len = num.length();
        BigInteger result = BigInteger.ZERO;
        for (int i = 0; i < len; i++) {
            int digit = num.charAt(i) - '0';
            if (digit < 0 || digit > 9) {
                throw new IllegalArgumentException("输入的整数中含有不合法的字符,请检查!");
            }
            result = result.multiply(BigInteger.valueOf(10L)).add(BigInteger.valueOf(digit));
        }
        return result;
    }

    public BigInteger calculateGCD(String a, String b) {
        return calculateGCD(standardize(a), standardize(b));
    }

    public BigInteger calculateGCD(BigInteger a, BigInteger b) {
        if (a.equals(BigInteger.ZERO) && b.equals(BigInteger.ZERO)) {
            throw new IllegalArgumentException("两个整数不能都是0!");
        }
        return doCalculateGCD(a, b);
    }

    private BigInteger doCalculateGCD(BigInteger a, BigInteger b) {
        if (b.equals(BigInteger.ZERO)) {
            return a;
        }
        return doCalculateGCD(b, a.mod(b));
    }
}

请将以上代码保存为 MyGCDCalculator.java。使用以下命令可以编译 MyGCDCalculator.java 并运行 MyGCDCalculator 类中的 main 方法。

bash 复制代码
javac MyGCDCalculator.java
java MyGCDCalculator

效果展示

异常情况 1:两个整数都是 0
异常情况 2:输入的整数中有不合法字符
正常情况 1:一个整数是 0,另一个是比较小的正整数
正常情况 2:一个整数是负数,另一个是正数(且有显式的 +
正常情况 3:两个比较大的 2 的幂次

这两个整数分别是 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 36 2^{36} </math>236 和 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 37 2^{37} </math>237,它们的最大公约数是 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 36 2^{36} </math>236

正常情况 4:一个比较大的 2 的幂次,一个比较大的 3 的幂次

这两个整数分别是 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 50 2^{50} </math>250 和 <math xmlns="http://www.w3.org/1998/Math/MathML"> 3 40 3^{40} </math>340,它们的最大公约数是 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 1 </math>1(因为两者没有任何共同的质因子)

说明

本文所展示的 java 代码是我自己写的(Intellij IDEA 会帮忙填充一些内容),读者朋友可以自由修改和使用。

相关推荐
brzhang2 小时前
我觉得可以试试 TOON —— 一个为 LLM 而生的极致压缩数据格式
前端·后端·架构
小安同学iter2 小时前
SQL50+Hot100系列(11.7)
java·算法·leetcode·hot100·sql50
苏三的开发日记2 小时前
库存预扣减之后,用户订单超时之后补偿库存的方案
后端
yivifu2 小时前
JavaScript Selection API详解
java·前端·javascript
zizisuo2 小时前
16000+字!Java集合笔记
java·开发语言
BeingACoder2 小时前
【SAA】SpringAI Alibaba学习笔记(二):提示词Prompt
java·人工智能·spring boot·笔记·prompt·saa·springai
熊猫钓鱼>_>2 小时前
Java面向对象核心面试技术考点深度解析
java·开发语言·面试·面向对象··class·oop
知其然亦知其所以然3 小时前
这波AI太原生了!SpringAI让PostgreSQL秒变智能数据库!
后端·spring·postgresql
黄暄3 小时前
微服务面试题(14题)
java·spring cloud·微服务·架构·java-rabbitmq·java-zookeeper