Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

command line arguments - ArrayIndexOutOfBoundsException when launching a java program

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

program arguments in NetBeans

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...