A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

slkdfj

初级黑马

  • 黑马币:0

  • 帖子:5

  • 精华:0

源程序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);   
        }

}

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1 鼓励

查看全部评分

4 个回复

倒序浏览

回帖奖励 +4

运行时没有传入参数,导致args的长度为0, int x=Integer.parseInt(args[0]);这里就出错了,字符串数组索引是以0开头的,args[0]是指数组中的第一个元素,如果数组中没有元素就会出现java.lang.ArrayIndexOutOfBoundsException
回复 使用道具 举报
Integer.parseInt(args[0]); 你这直接调用 args[0] 肯定会报 java.lang.ArrayIndexOutOfBoundsException 异常的,因为JVM调用主函数的时候传入的是 new String[0];
回复 使用道具 举报
没有传入参数,args为空,肯定报空指针异常
回复 使用道具 举报
  1. /*
  2. 你代码逻辑就有问题,如果args.length<0,你哪来的args[0]呢?
  3. 这里必然会抛java.lang.ArrayIndexOutOfBoundsException 异常
  4. 想求绝对值的话,你是想这么实现吧
  5. */
  6. public class if1
  7. {
  8.   public static void main(String args[])
  9.     {
  10.            if(args.length>0)
  11.                 {
  12.                    int x=Integer.parseInt(args[0]);
  13.                    int y=x;
  14.                    if(x<0)//如果x<0,返回0-x即他的绝对值,而不是判断args的长度
  15.                         {
  16.                             y=0-x;
  17.                         }
  18.       
  19.                      System.out.println("x绝对值是"+y);   
  20.                 }
  21.      }

  22. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马