package FirstDemo; import java.util.Scanner; public class demo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 输入初始进制,要转换的进制数和目标进制 System.out.print("请输入初始进制: "); int sourceBase = scanner.nextInt(); System.out.print("请输入要转换的数字: "); String sourceNumber = scanner.next(); System.out.print("请输入目标进制: "); int targetBase = scanner.nextInt(); int decimalValue = toDecimal(sourceNumber, sourceBase); String targetNumber = fromDecimal(decimalValue, targetBase); System.out.printf("转换成" + targetBase +"进制的结果为: %s\n", targetNumber); scanner.close(); } // 将输入转换为10进制 public static int toDecimal(String number, int base) { return Integer.parseInt(number, base); } //将转换后的10进制数转换为R进制数 public static String fromDecimal(int number, int base) { StringBuilder sb = new StringBuilder(); while (number > 0) { int remainder = number % base; // 对于大于9的数字,用字母A-F表示 if (remainder >= 10) { sb.append((char) ('A' + remainder - 10)); } else { sb.append(remainder); } number /= base; } return sb.reverse().toString(); //反转字符串以得到正确的顺序 } }