将键盘输入的数转为二进制形式


import java.util.Scanner;

/**
* 将键盘上输入的一个字符串转换成十进制整数,然后打印出这个十进制整数对应的二进制形式。<br>
* <br>
* 这个程序要考虑输入的字符串不能转换成一个十进制整数的情况,并对转换失败的原因要区分出是数字太大,<br>
* 还是其中包含有非数字字符的情况。<br>
* 提示:十进制数转二进制数的方式是用这个数除以2,余数就是二进制数的最低位,<br>
* 接着再用得到的商作为被除数去除以2,这次得到的余数就是次低位,如此循环,直到被除数为0为止。<br>
* 其实,只要明白了打印出一个十进制数的每一位的方式(不断除以10,得到的余数就分别是个位,十位,百位),<br>
* 就很容易理解十进制数转二进制数的这种方式。
*
* @author 享受JAVA(java2000.net)
*/
public class T3 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int num = 0;
try {
num = strToInt(str);
} catch (NumberFormatException ex) {
System.out.println(ex.getMessage());
return;
}
System.out.println("num=" + num);
System.out.println("二进制为:" + toBinaryString(num));
}

public static String toBinaryString(int num) {
StringBuilder b = new StringBuilder();
try {
while (num > 0) {
b.insert(0, num % 2);
num >>>= 1;
}
return b.toString();
} finally {
b.delete(0, b.length());
b = null;
}
}

public static int strToInt(String s) {
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
}
multmin = limit / 10;
if (i < max) {
digit = Character.digit(s.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("字符串格式不正确: \"" + s + "\"");
} else {
result = -digit;
}
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), 10);
if (digit < 0) {
throw new NumberFormatException("字符串格式不正确: \"" + s + "\"");
}
if (result < multmin) {
throw new NumberFormatException("数字超过最大允许范围:: \"" + s + "\"");
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException("数字超过最大允许范围: \"" + s + "\"");
}
result -= digit;
}
} else {
throw new NumberFormatException("字符串为空: \"" + s + "\"");
}
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw new NumberFormatException("不能只有负号: \"" + s + "\"");
}
} else {
return -result;
}
}
}


注解
StringBuffer 上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符添加或插入到字符串缓冲区中。append 方法始终将这些字符添加到缓冲区的末端;而 insert 方法则在指定的点添加字符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值