黑马程序员技术交流社区
标题:
java if语句小程序 报错 Exception in thread "main"
[打印本页]
作者:
slkdfj
时间:
2014-4-20 23:10
标题:
java if语句小程序 报错 Exception in thread "main"
源程序public class if1
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
int y=x;
if(args.length<0)
{
y=0-x;
}
System.out.println("x绝对值是"+y);
}
}
作者:
hsen
时间:
2014-4-20 23:10
运行时没有传入参数,导致args的长度为0, int x=Integer.parseInt(args[0]);这里就出错了,字符串数组索引是以0开头的,args[0]是指数组中的第一个元素,如果数组中没有元素就会出现java.lang.ArrayIndexOutOfBoundsException
作者:
tjsyj
时间:
2014-4-20 23:21
Integer.parseInt(args[0]); 你这直接调用 args[0] 肯定会报 java.lang.ArrayIndexOutOfBoundsException 异常的,因为JVM调用主函数的时候传入的是 new String[0];
作者:
hhmm665544
时间:
2014-4-21 01:35
没有传入参数,args为空,肯定报空指针异常
作者:
忘川
时间:
2014-4-21 08:24
/*
你代码逻辑就有问题,如果args.length<0,你哪来的args[0]呢?
这里必然会抛java.lang.ArrayIndexOutOfBoundsException 异常
想求绝对值的话,你是想这么实现吧
*/
public class if1
{
public static void main(String args[])
{
if(args.length>0)
{
int x=Integer.parseInt(args[0]);
int y=x;
if(x<0)//如果x<0,返回0-x即他的绝对值,而不是判断args的长度
{
y=0-x;
}
System.out.println("x绝对值是"+y);
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2