|
|
@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public class Calculator {
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
|
|
|
Scanner scanner = new Scanner(System.in);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
System.out.print("请输入要转换的数:");
|
|
|
|
|
|
|
|
String num = scanner.nextLine();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
System.out.print("请输入源进制(2-16):");
|
|
|
|
|
|
|
|
int fromBase = scanner.nextInt();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
System.out.print("请输入目标进制(2-16):");
|
|
|
|
|
|
|
|
int toBase = scanner.nextInt();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 调用转换方法
|
|
|
|
|
|
|
|
String converted = convertBase(num, fromBase, toBase);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
System.out.printf("%s (base %d) 转换为 base %d 是 %s%n", num, fromBase, toBase, converted);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static String convertBase(String num, int fromBase, int toBase) {
|
|
|
|
|
|
|
|
// 将给定的fromBase进制数转换为十进制数
|
|
|
|
|
|
|
|
int decimalNum = Integer.parseInt(num, fromBase);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 定义字符集以表示大于10的进制数
|
|
|
|
|
|
|
|
char[] digits = "0123456789ABCDEF".toCharArray();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 如果目标进制是10,则直接返回decimalNum
|
|
|
|
|
|
|
|
if (toBase == 10) {
|
|
|
|
|
|
|
|
return String.valueOf(decimalNum);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 否则,从十进制转换为目标进制
|
|
|
|
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
|
|
|
|
while (decimalNum > 0) {
|
|
|
|
|
|
|
|
int remainder = decimalNum % toBase;
|
|
|
|
|
|
|
|
result.insert(0, digits[remainder]);
|
|
|
|
|
|
|
|
decimalNum /= toBase;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return result.toString();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|