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

相关推荐
马剑威(威哥爱编程)14 分钟前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL19 分钟前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
V***u4531 小时前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿1 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t9191 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08291 小时前
【监控】spring actuator源码速读
java·spring boot·spring
麦麦鸡腿堡2 小时前
Java_网络编程_InetAddress类与Socket类
java·服务器·网络
@大迁世界2 小时前
相信我兄弟:Cloudflare Rust 的 .unwrap() 方法在 330 多个数据中心引发了恐慌
开发语言·后端·rust
vx_dmxq2112 小时前
【PHP考研互助系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·mysql·考研·微信小程序·小程序·php
5***g2982 小时前
新手如何快速搭建一个Springboot项目
java·spring boot·后端