public class TestDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String st=null;
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//键盘录入
try {
st=bufr.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//调用转换二进制方法
toBin(st);
}
public static void toBin(String st){
Integer num=null;
boolean blag=true;
int x=0;
while(x<st.length()){
char c=st.charAt(x);
if(st.charAt(0)=='0'){
System.out.println("第一位是零");
blag=false;
break;
}
if(!(c>47 && c<58)){
System.out.println("出现非数字字符");
blag=false;
break;
}
x++;
}
if(Integer.parseInt(st)>Integer.MAX_VALUE){
System.out.println("数字太大");
blag=false;
}
if(blag){
StringBuffer sbf=new StringBuffer();//定义一个容器
num = Integer.valueOf(st);
while(num>0){
sbf.append(num%2);
num >>>= 1;// 无符号右移1位,相当于num = num / 2;只不过效率更高
}
System.out.println(sbf.reverse());
}
else
System.out.println("请检查!!!");
}
}
输入12345678987654结果是
12345678987654
Exception in thread "main" java.lang.NumberFormatException: For input string: "12345678987654"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.itheima.Test9.toBin(Test9.java:52)
at com.itheima.Test9.main(Test9.java:32)
不是应该输出数字太大吗 不懂求解!!!
|