You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jzzh/Calculator.java

45 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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();
}
}