java 十进制转2进制的小程序

来源:百度知道 编辑:UC知道 时间:2024/06/16 02:10:12
编写一个程序,它先将键盘上输入的一个字符串转换成十进制整数,然后打印出这个十进制整数对应的二进制形式。这个程序要考虑输入的字符串不能转换成一个十进制整数的情况,并对转换失败的原因要区分出是数字太大,还是其中包含有非数字字符的情况。
提示:十进制数转二进制数的方式是用这个数除以2,余数就是二进制数的最低位,接着再用得到的商作为被除数去除以2,这次得到的余数就是次低位,如此循环,直到被除数为0为止。其实,只要明白了打印出一个十进制数的每一位的方式(不断除以10,得到的余数就分别是个位,十位,百位),就很容易理解十进制数转二进制数的这种方式。

帮你写好了,呵呵,程序如下:
import java.io.*;

public class DecimaltoBinary {

public static void toBinary(int value) {
int count = 1;
int m = 2;
while (value >= m) {
++count;
m *= 2;
}
int array[] = new int[count];
int i = 0;
while (value != 0) {
array[i] = value % 2;
value /= 2;
i++;
}
for (int k = array.length - 1; k >= 0; k--)
System.out.print(array[k]);
System.out.print("\t");
}

public static String StringInput() {
String str = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
str = br.readLine();
} catch (IOException e) {
System.out.println("输入输出错误");
}
return str;
}

public static void main(String[] args) throws Exception {
System.out.print("请输入任意一个整数:");