2

I am using Eclipse ADT to learn Java. I used ADT for an intro to Android course on the MOOC coursera platform. Going through that course, I see that learning Java is needed.

I am working through a java book: JAVA in easy steps by Mike Mcgrath

This lesson is teaching: Passing an argument. The code I have entered in ADT is:

package com.javatutorial.hello;

public class Option {
    public static void main ( String[] args ) {
        if ( args[0].equals( "-en"))
        {
            System.out.println( "English option");
        }
        else if ( args[0].equals( "-es"))
        {
            System.out.println( "Spanish option");
        }
        else System.out.println( "Unrecognized option");
    }
}

When I run the program I get this exception error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at com.javatutorial.hello.Option.main(Option.java:5)

So far I have figured out solutions to problems I have run into, but need help for this one. Thank you in advance for your help.

0

4 Answers 4

2

You're probably not passing any arguments to the function. In the Run As dialog, you need to set the arguments to the program. If this isn't set correctly, your index into the array is invalid.

Alternatively, you can check that args has been properly passed with options by checking

if(args.length >= 1) {
    // now try to index into args.
}

This correctly prevents the ArrayIndexOutOfBoundsException in the case that the user isn't required to pass an option.

Sign up to request clarification or add additional context in comments.

Comments

0

When you run the application you need to define almost one input argument due you are using it (args[0])

Comments

0

Try putting a control first, also you HAVE to pass it some argument.

package com.javatutorial.hello;


public class Option {
    public static void main ( String[] args ) {

      if(args.length!=0){
        if ( args[0].equals( "-en"))
        {
            System.out.println( "English option");
        }
        else if ( args[0].equals( "-es"))
        {
            System.out.println( "Spanish option");
        }
        else System.out.println( "Unrecognized option");
    }}
}

Comments

0

Run your application from cmd (Windows) or terminal (if you work on Linux):

javac Option.java
java Option -en

You should add at least one argument after java Option

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.