|
|
|
|
import javax.swing.JOptionPane;
|
|
|
|
|
|
|
|
|
|
public class jinzhi_lj {
|
|
|
|
|
|
|
|
|
|
// 将数字从 'fromBase' 转换为 'toBase'
|
|
|
|
|
public static String convertBase(String number, int fromBase, int toBase) {
|
|
|
|
|
// 第一步:从 'fromBase' 转换为十进制(base 10)
|
|
|
|
|
int decimalNumber = 0;
|
|
|
|
|
int length = number.length();
|
|
|
|
|
|
|
|
|
|
// 将输入数字转换为十进制
|
|
|
|
|
for (int i = 0; i < length; i++) {
|
|
|
|
|
char digit = number.charAt(length - 1 - i);
|
|
|
|
|
int value;
|
|
|
|
|
if (Character.isDigit(digit)) {
|
|
|
|
|
value = digit - '0'; // 将字符转换为 0-9 的整数
|
|
|
|
|
} else {
|
|
|
|
|
value = Character.toUpperCase(digit) - 'A' + 10; // 将字符转换为 A-F 的整数
|
|
|
|
|
}
|
|
|
|
|
decimalNumber += value * Math.pow(fromBase, i);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 第二步:从十进制转换为目标进制
|
|
|
|
|
if (decimalNumber == 0) {
|
|
|
|
|
return "0"; // 如果数字为零,返回 "0"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
// 将十进制数字转换为目标基数
|
|
|
|
|
while (decimalNumber > 0) {
|
|
|
|
|
int remainder = decimalNumber % toBase;
|
|
|
|
|
if (remainder < 10) {
|
|
|
|
|
result.append((char) (remainder + '0')); // 添加 0-9 的数字
|
|
|
|
|
} else {
|
|
|
|
|
result.append((char) (remainder - 10 + 'A')); // 添加 A-F 的字母
|
|
|
|
|
}
|
|
|
|
|
decimalNumber /= toBase;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 反转结果,因为我们是从后向前构建的
|
|
|
|
|
return result.reverse().toString();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
// 输入数字和基数
|
|
|
|
|
String number = JOptionPane.showInputDialog("请输入数字:");
|
|
|
|
|
String fromBaseInput = JOptionPane.showInputDialog("请输入原始进制 (2 到 16):");
|
|
|
|
|
int fromBase = Integer.parseInt(fromBaseInput);
|
|
|
|
|
String toBaseInput = JOptionPane.showInputDialog("请输入目标进制 (2 到 16):");
|
|
|
|
|
int toBase = Integer.parseInt(toBaseInput);
|
|
|
|
|
|
|
|
|
|
// 验证基数
|
|
|
|
|
if (fromBase < 2 || fromBase > 16 || toBase < 2 || toBase > 16) {
|
|
|
|
|
JOptionPane.showMessageDialog(null, "基数必须在 2 到 16 之间。");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 转换数字并打印结果11
|
|
|
|
|
String result = convertBase(number, fromBase, toBase);
|
|
|
|
|
String message = "进制为 " + fromBase + " 的数: " + number + " 在进制为 " + toBase + " 的数是: " + result;
|
|
|
|
|
|
|
|
|
|
// 使用弹窗显示结果
|
|
|
|
|
JOptionPane.showMessageDialog(null, message);
|
|
|
|
|
}
|
|
|
|
|
}
|