问题
I am currently working on an assignment but there seems to be a problem when running my code.
public class caesar {
public static void main(String args[]) {
String inputString = args[0];
char inputArray[] = inputString.toCharArray();
int shiftLength = Integer.parseInt(args[1]);
System.out.println("Input: " + inputString);
String outputString = "";
This is the error I am receiving:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at caesar.main(caesar.java:3)
回答1:
You are not passing command line arguments to your program and don't check whether they are passed. To pass arguments launch your program like
java caesar arg0 arg1
For example:
java caesar somestring 10
To do this in NetBeans 8.0.2 IDE, open Project Properties, select the Run item, then specify the arguments there:
You may probably also want to check the number of passed arguments in advance to output the friendly error message. For example:
public static void main(String args[]) {
if(args.length != 2) {
System.err.println("Usage: java caesar <inputString> <shift>");
return;
}
... // the rest of your code
}
回答2:
Tagir's Answer explained how to pass arguments to the Java class. I want to explain what the exception java.lang.ArrayIndexOutOfBoundsException
means.
ArrayIndexOutOfBoundsException
occurs when you try to access an element in an array which does not exists. In your case you are trying to access the first element but the array is empty that's the reason you are getting an ArrayIndexOutOfBoundsException
.
Before accessing an array element by index make sure the size of that array is at least index+1. If the index is n
the size should be n+1
if not you will get the exception.
来源:https://stackoverflow.com/questions/32042638/arrayindexoutofboundsexception-when-launching-a-java-program