以下是Java实现十进制到各种进制的转换的代码示例:
import java.util.Scanner;
public class DecimalToOtherBases {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimalNumber = scanner.nextInt();
System.out.println("Binary: " + convertToBase(decimalNumber, 2));
System.out.println("Octal: " + convertToBase(decimalNumber, 8));
System.out.println("Hexadecimal: " + convertToBase(decimalNumber, 16));
scanner.close();
}
public static String convertToBase(int decimalNumber, int base) {
if (decimalNumber == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (decimalNumber > 0) {
int remainder = decimalNumber % base;
if (remainder < 10) {
result.insert(0, remainder);
} else {
result.insert(0, (char) ('A' + remainder - 10));
}
decimalNumber /= base;
}
return result.toString();
}
}
这段代码可以让用户输入一个十进制数,然后将其转换为二进制、八进制和十六进制表示。实现了基本的转换功能,满足你的要求。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。