为什么`java.lang.ArrayIndexOutOfBoundsException:0`和`main`方法参数 [英] Why `java.lang.ArrayIndexOutOfBoundsException: 0` with `main` method arguments

查看:50
本文介绍了为什么`java.lang.ArrayIndexOutOfBoundsException:0`和`main`方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中的错误在哪里?

Where is the mistake in my code?

package My;

import java.text.SimpleDateFormat; 
import java.util.Date; 
public class Hello { 
    public static void main(String[] args) { 
        Date now = new Date(); 
        SimpleDateFormat formatter = 
        new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss"); 
        String formattedDate = formatter.format(now); 
        System.out.println(formattedDate + "> Hello, " + args[0] + "!"); 
    }
}

输出是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at My.Hello.main(Hello.java:11)

} 

推荐答案

您需要从命令行传递参数.请参考

You need to pass arguments from the command line.Refer the official docs.

package My;

import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {
    public static void main(String[] args) {
        Date now = new Date();
        SimpleDateFormat formatter =
        new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
        String formattedDate = formatter.format(now);
        System.out.println(formattedDate + "> Hello, " + args[0] + "!");
    }
}

编译和执行:

这篇关于为什么`java.lang.ArrayIndexOutOfBoundsException:0`和`main`方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆