[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 会帮忙填充一些内容),读者朋友可以自由修改和使用。

相关推荐
Ahtacca1 分钟前
Maven 入门:项目管理与依赖管理的核心玩法
java·maven
a程序小傲7 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
想用offer打牌11 分钟前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
⑩-11 分钟前
Java四种线程创建方式
java·开发语言
月光在发光12 分钟前
22_GDB调试记录(未完成)
java·开发语言
222you14 分钟前
SpringAOP的介绍和入门
java·开发语言·spring
Violet_YSWY23 分钟前
哪些常量用枚举,哪些用类
java
shoubepatien24 分钟前
JAVA -- 09
java·开发语言
kong790692824 分钟前
Java新特性-(三)程序流程控制
java·java新特性
愿你天黑有灯下雨有伞25 分钟前
Spring Boot 使用FastExcel实现多级表头动态数据填充导出
java·faseexcel