Why `java.lang.ArrayIndexOutOfBoundsException: 0` with `main` method arguments [closed]

空扰寡人 提交于 2021-02-17 07:22:24

问题


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] + "!"); 
    }
}

out put is

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

} 

回答1:


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

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] + "!");
    }
}

Compilation and Execution:

enter image description here




回答2:


JVM throw exception bcoz no element exist at index 0 in the array.So provide the parameter during running the class or just add below code so that no exception will raise :

    if(args.length >= 1)
       {
           System.out.println(formattedDate + "> Hello, " + args[0] + "!"); 
       }

Pass the argument as below :

java My.Hello BHARAT


来源:https://stackoverflow.com/questions/22131816/why-java-lang-arrayindexoutofboundsexception-0-with-main-method-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!