真实击剑
93.36 MB · 2025-11-22
Swing 生成一个最大公约数计算器最终的效果如下图所示 ⬇️
我来说说核心的步骤。
欧几里得算法是计算最大公约数的经典算法。如果我们使用 java 中的 BigInteger,那么从理论上讲,可以计算出任意大小的两个整数的最大公约数(按照定义,这两个整数不能同时为 )。
如果用 Swing 来生成用户界面的话,用户的输入会是 String。我们需要写点将 String 转化为 BigInteger 的代码。
有了上述的思路后,可以先把计算最大公约数和 String -> BigInteger 转化的代码写好 ⬇️
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 方法已经删除了) ⬇️
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 方法。
javac MyGCDCalculator.java
java MyGCDCalculator
+)这两个整数分别是 和 ,它们的最大公约数是
这两个整数分别是 和 ,它们的最大公约数是 (因为两者没有任何共同的质因子)
本文所展示的 java 代码是我自己写的(Intellij IDEA 会帮忙填充一些内容),读者朋友可以自由修改和使用。