问题
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:
回答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