程序运行时总是显示有错误,求修改

   阅读
程序运行时总是显示有异常,求修改
import java.io.*;
class Demo065
{
public static void main(String[] args)throws IOException
{
zhuanhuan c=new zhuanhuan();
c.zhch();
}
}
class zhuanhuan
{
public  void zhch()throws IOException//从键盘输入数字,先转换成16进制,然后转换成2进制
{
     System.out.println("Please input the hex number");
     InputStream in=System.in;
     int x=in.read();
StringBuilder sb=new StringBuilder();
while(x!=0)//转换成十六进制
{
int temp=x%16;
x=x/16;
if(temp>9)
{
sb.append((char)((temp-10)+'a'));
}
else sb.append(temp);
}
int i=Integer.parseInt(sb.toString(),2);//调用系统方法转换成2进制
System.out.println(i);
}

}

------解决方案--------------------
int i=Integer.parseInt(sb.toString(),2);//调用系统方法转换成2进制

这个方法不是将前面的字符串转换成2进制,而是将前面的二进制字符串换算成十进制形式

楼主试试int i=Integer.parseInt("100",2)然后打印i的值,肯定是4
------解决方案--------------------
引用:
import java.io.*;
class Demo065
{
public static void main(String[] args)throws IOException
{
zhuanhuan c=new zhuanhuan();
c.zhch();
}
}
class zhuanhuan
{
public  void zhch()throws IOException//从键盘输入数字,先转换成16进制,然后转换成2进制
{
     System.out.println("Please input the hex number");
     InputStream in=System.in;
     int x=in.read();
StringBuilder sb=new StringBuilder();
while(x!=0)//转换成十六进制
{
int temp=x%16;
x=x/16;
if(temp>9)
{
sb.append((char)((temp-10)+'a'));
}
else sb.append(temp);
}
int i=Integer.parseInt(sb.toString(),2);//调用系统方法转换成2进制
System.out.println(i);
}

}

InputStream in=System.in;
     int x=in.read();
这样读取其实是错误的,in.read()是从控制台中读取一个字符,然后将读入的字符的ASCII码转换成int型,你打印出x出来看看,出入5的时候出来的结果是53(就是字符5的ascii码)
可以用Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

Quote: 引用:

Quote: 引用:

你的main方法呢?

有吧,你看看

你把转换为字符串的那行先注释掉,改为:
        int j= Integer.parseInt("0XA1", 2);
        System.out.println(j);
这样你就知道为什么了!

我知道你们得意思,我也那样试过,不过我想把这题改成正确的,暂且不考虑int i=Integer.parseInt(sb.toString(),2);//调用系统方法转换成2进制-------这句备注有误。运行时错误提示是Exception in thread "main" java.lang.NumberFormatException: For input string: "5
3",其中53与键盘输入的数据有关,不是固定的。
改算法!

我想知道哪里错了呀,只要能运行一个特例都行,只想明白错在哪里,结果不重要

我对代码进行调试:

然后进入:

查找454行jdk中的实现:

可以发现16进制中X是基数不在 MIN_RADIX <= radix <= MAX_RADIX 范围之内,因此返回-1,接着跟着程序就抛出相干异常!
阅读