We’d like to remind Forumites to please avoid political debate on the Forum.

This is to keep it a safe and useful space for MoneySaving discussions. Threads that are – or become – political in nature may be removed in line with the Forum’s rules. Thank you for your understanding.

📨 Have you signed up to the Forum's new Email Digest yet? Get a selection of trending threads sent straight to your inbox daily, weekly or monthly!
The Forum now has a brand new text editor, adding a bunch of handy features to use when creating posts. Read more in our how-to guide

Java - passing an argument

Hi,

I'm working through "Java in Easy Steps" and have hit a problem where the code I've been given isn't doing what it should.
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" );
}
}
I don't know where args[0] has been declared, and I've tried a couple of things. The book just says to type in the above code and compile /run and it should just output one of the options.

I tried adding the args[0] as follows:
args[0] = "-en";
before the if, else if, else statement, but the output is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Option.main(Option.java:5)
It's the first of the examples in the book that isn't working after following instructions and I can't find errata on the book's website.

There aren't any problems or warnings with the code.

Please could anyone advise how to get it to compile?

Thanks

Comments

  • RobTang
    RobTang Posts: 1,064 Forumite
    args is a string array which is passed in from the command line.
    Its declared as a parameter for the "main()" function.

    Its likely you are starting your program with no arguments therefore the variable args will be zero length array.
    Your getting the error because you are trying to access an element in the array that does not exist.

    if you're calling the compiled jar from the command line it should be something like this.

    java -jar yourFile.jar -eng

    args[0] will now equal -eng

    If you using an IDE you will need to set your run options to pass the argument,
  • MercenaryMan
    MercenaryMan Posts: 53 Forumite
    edited 10 March 2013 at 11:42PM
    You can find the usage of Oracle's Java implementation in the JDK Development Tools documentation.

    The general usage will be:
    java <java_options> ClassName <program_arguments>
    

    In your case:
    java -cp <dir> Option -en
    

    ...where <dir> is the directory containing Option.class.

    EDIT: I should add that you may find a more specialized forum like JavaRanch useful for learning Java basics.
  • Ectophile
    Ectophile Posts: 8,299 Forumite
    Part of the Furniture 1,000 Posts Photogenic Name Dropper
    There's no specific declaration of args[0], but the main function is expecting an array of Strings to be passed in.

    In Java, like several other programming languages, array indexes start at 0, so args[0] is the first string in the array.

    If you pass in an empty array (in this case, if you don't add any arguments to the command line), then it goes wrong.

    Ideally, you should check args.length to detect this case, before accessing args[0].
    If it sticks, force it.
    If it breaks, well it wasn't working right anyway.
  • gb12345
    gb12345 Posts: 3,055 Forumite
    Ectophile wrote: »
    Ideally, you should check args.length to detect this case, before accessing args[0].

    What you really want is something like this
    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" );
    }
    else
    {
        System.out.println( "Invalid call please use argument -en or -es"; );
    }
    
  • you need to pass the argument to the main argument. so compile the code as suggested in the book "javac Option.java" then do "java Option -en" and you have passed the argument to the file. repeat with "java Option -es" to see the outcome!
This discussion has been closed.
Meet your Ambassadors

🚀 Getting Started

Hi new member!

Our Getting Started Guide will help you get the most out of the Forum

Categories

  • All Categories
  • 353.4K Banking & Borrowing
  • 254.1K Reduce Debt & Boost Income
  • 455K Spending & Discounts
  • 246.5K Work, Benefits & Business
  • 602.8K Mortgages, Homes & Bills
  • 178K Life & Family
  • 260.5K Travel & Transport
  • 1.5M Hobbies & Leisure
  • 16K Discuss & Feedback
  • 37.7K Read-Only Boards

Is this how you want to be seen?

We see you are using a default avatar. It takes only a few seconds to pick a picture.