利用JAVA编写程序 要求:(1)可输入二进制、八进制、十进制、十六进制数; (2)将已输入的数转换成其余进制的数; (3)具有输入输出界面。
时间: 2024-03-09 12:44:46 浏览: 15
好的,以下是一个示例程序,可以实现输入任意进制的数,并转换为其余进制的数,同时具有输入输出界面。
```java
import java.util.Scanner;
public class NumberConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
String input = scanner.nextLine();
System.out.print("请输入该整数的进制(2、8、10、16):");
int inputBase = scanner.nextInt();
scanner.close();
// 将输入的数转换为10进制数
int decimal = Integer.parseInt(input, inputBase);
// 转换为二进制数
String binary = Integer.toBinaryString(decimal);
// 转换为八进制数
String octal = Integer.toOctalString(decimal);
// 转换为十六进制数
String hex = Integer.toHexString(decimal);
System.out.println("二进制数为:" + binary);
System.out.println("八进制数为:" + octal);
System.out.println("十进制数为:" + decimal);
System.out.println("十六进制数为:" + hex);
}
}
```
在这个程序中,我们首先使用Scanner类获取用户输入的整数和进制。然后,我们使用Integer.parseInt()方法将输入的数转换为10进制数。接下来,我们使用Integer.toBinaryString()、Integer.toOctalString()和Integer.toHexString()方法将10进制数转换为二进制、八进制和十六进制数。最后,我们输出转换后的结果。
当然,这个程序只是一个简单的示例,您可以根据自己的需求进行扩展和改进。例如,您可以添加更多的进制选项,让用户更方便地使用程序。同时,您也可以对转换算法进行改进,增强其准确性和可靠性。