(int)x与Integer.parseInt(x)的区别

snihcel 2010-11-08 03:01:47
class test02
{
public static void main(String[] args)
{
char s2='a';
String s1="12";
double x=Double.parseDouble(s1);
int y=(int)s2;//Integer.parseInt(s2);
System.out.println(x+y);
}
}

结果是109.0
如果使用Integer.parseInt(s2);
却会报错

但是下面的代码
class test02
{
public static void main(String[] args)
{
String s1="0.5",s2="12";
double x=Double.parseDouble(s1);
int y=Integer.parseInt(s2);//(int)s2;
System.out.println(x+y);
}
}
输出结果是12.5 使用(int)就会报错这是为什么呢

...全文
1293 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
snihcel 2010-11-15
  • 打赏
  • 举报
回复
谢谢楼上的,有时间帮忙点一点,现在作代码幸苦啊,ip8000.com sql8.net
tianhandigeng1498 2010-11-08
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wanghantong 的回复:]

给你看两个代码
Java code
Integer a = new Integer(10);
Integer b = new Integer(10);
System.out.println(a==b); ----false
System.out.println(a.equals(b)); ---- true


Integer是类类型的。
……
[/Quote]
确实啊,跟楼主问的不相关,你想表达的就是Integer是和String一样是吧?
ETCentury 2010-11-08
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wanghantong 的回复:]

给你看两个代码
Java code
Integer a = new Integer(10);
Integer b = new Integer(10);
System.out.println(a==b); ----false
System.out.println(a.equals(b)); ---- true


Integer是类类型的。
……
[/Quote]

感觉你说这个和楼主问的不相关
桐桐-Dragon 2010-11-08
  • 打赏
  • 举报
回复
给你看两个代码
Integer a = new Integer(10);
Integer b = new Integer(10);
System.out.println(a==b); ----false
System.out.println(a.equals(b)); ---- true

Integer是类类型的。
其他的说不好,还是多看看书吧。希望能帮到你
magong 2010-11-08
  • 打赏
  • 举报
回复
1楼已经指出来了,我来解释一下。
上面那题:
s2是char,char虽然表示字符,但依然可以强制类型转换为整数。'a'转换后的整数值就是其码97。
若将'a'字符送给parseInt,因为char不是String,当然报错。这里用parseInt("a",16)可以得到10.

下面那题:
s2是String了,强制类型转换为int就不行了。
学习Java中 2010-11-08
  • 打赏
  • 举报
回复
s2 是char型
static int parseInt(String s)
将字符串参数作为有符号的十进制整数进行分析。
static int parseInt(String s, int radix)
使用第二个参数指定的基数,将字符串参数解析为有符号的整数。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧