贴代码:
package JavaSE.practise;
import java.util.Scanner;
public class ArrayTest7 {
public static void main(String[] args) {
System.out.println("---欢迎使用进制转换工具---");
Scanner input = new Scanner(System.in);
String flag = "y";
do {
System.out.print("请输入一个十进制数:");
int num = input.nextInt();
System.out.print(num + "的二进制数是:");
toBin(num);
System.out.println();
System.out.print(num + "的八进制数是:");
toOct(num);
System.out.println();
System.out.print(num + "的十六进制数是:");
toHex(num);
System.out.println();
System.out.println("-------------------");
System.out.println("是否继续使用,'y'或'n'?");
flag = input.next();
} while ("y".equals(flag));
System.out.println("谢谢使用");
}
/**
* 进制转换方法
*
* @param num
* 参与转换的数字
* @param base
* “&”的位数
* @param offset
* 右移的位数
*/
public static void trans(int num, int base, int offset) {
char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] arr = new char[32];
int pos = arr.length;
while (num != 0) {
int temp = num & base;
arr[--pos] = chs[temp];
num = num >>> offset;
}
for (int x = pos; x < arr.length; x++) {
System.out.print(arr[x]);
}
}
/**
* 二进制转换
*/
public static void toBin(int num) {
trans(num, 1, 1);
}
/**
* 八进制转换
*/
public static void toOct(int num) {
trans(num, 7, 3);
}
/**
* 十六进制转换
*/
public static void toHex(int num) {
trans(num, 15, 4);
}
}
|
|