用java编写以小程序:定义一整数把他的二进制,八进制,十六进制表示在屏幕上显示并输出来!

2024-12-03 08:09:16
推荐回答(3个)
回答1:

这是自己写的 没用Integer中的方法 很简单的
public class To {
private static char[] a = { '0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'};
/**
* @param args
*/
public static void main(String[] args) {
int number = 10;
System.out.println(number + "二进制: " + toNumber(number, 2));
System.out.println(number + "八进制: " + toNumber(number, 8));
System.out.println(number + "十六进制: " + toNumber(number, 16));
}

public static String toNumber(int number, int n) {
String str="";
for(int i = 0; i < n; i ++) {
if(number == i) {
str=a[i] + str;
return str;
}
}
str = a[number % n] + str;
str = toNumber(number/n, n) + str;
return str;
}
}

回答2:

public class Test {
public static void main(String[] args) {
int n = 100;
System.out.println("二进制:" + Integer.toBinaryString(n));
System.out.println("八进制:" + Integer.toOctalString(n));
System.out.println("十六进制:" + Integer.toHexString(n));
}
}

回答3:

public class Test {
public static void main(String[] args) {
int a = 10;
System.out.println(Integer.toString(a, 10));
System.out.println(Integer.toString(a, 16));
System.out.println(Integer.toString(a, 8));
System.out.println(Integer.toString(a, 2));
}
}