如何在程序里选着指定数字进制?

来源:百度知道 编辑:UC知道 时间:2024/05/03 06:37:22
程序可以选择所需的运算进制数(比如,二进制,三进制,十进制),然后输入两个数字,计算出二者之和。
例如:
输入:2
1
10
输出:11
以此类推

只有2,8,10,16进制,不存在三进制...

代码实现如下,谨供参考:

import java.util.Scanner;

public class MultiIntPlusOperation {
int type;
String arg1, arg2;
String result;

public void input() {
// 输入
Scanner sc = new Scanner(System.in);
// 输入进制
do {
System.err.println("请选择输入参数的类型:\n(2,二进制 8,八进制 10,十进制 16,十六进制)");
type = sc.nextInt();
sc.nextLine();
} while (type != 2 && type != 8 && type != 10 && type != 16);

// 输入第一个参数
System.err.println("请选择输入第一个参数:");
arg1 = sc.next();
sc.nextLine();

// 输入第二个参数
System.err.println("请选择输入第二个参数:");
arg2 = sc.next();
sc.nextLine();
}

public void plus() {
// 根据不同的进制,进行不同的计算,返回不同进制格式的值
try {
// 判断进制
switch (type) {
case 2:
result = Integer.toBinaryString(Integer.parseInt(arg1, type)
+