Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

main( String args[] ) problem

1 view
Skip to first unread message

aseru

unread,
Feb 9, 2002, 5:42:44 PM2/9/02
to
My understanding is that the following code would take in any command line
arguments and put them in to a array called args but when I run this ie.
java test 6
I get the following error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at Test.main(Test.java:14)


import javax.swing.*;
import java.awt.*;

class Test
{

public static void main( String args[] )
{

System.out.println( args[ 0 ]);

}
}


Patricia Shanahan

unread,
Feb 9, 2002, 7:14:54 PM2/9/02
to
There seems to be an inconsistency, since the class is called "Test" but
you say you are running "test". The JVM is complaining about line 14 in
Test.java, but the posted code does not have an array reference on line
14.

One possible cause of your trouble is confusion about what class is
running. I would take the sample code and change the class name to
something distinctive that you have never previously used as a class
name. Add a distinctive output before the attempt to access the array.

Patricia

Lee Ryman

unread,
Feb 10, 2002, 5:43:12 AM2/10/02
to
Besides that you should be catching ArrayIndexOutOfBounds exceptions in this
situation. It only takes someone not to pass in the correct number of
command-line parametres in and your whole program comes to a swift halt.
(either that or determine how big the argument array is before you start
itterating through it). If your program requires some command-line args and
the user doesn't pass any in then its always a good idea to provide some
usage text on execution.

Regards,

Lee


aseru

unread,
Feb 10, 2002, 9:31:51 AM2/10/02
to
I have been running Java Test 4
I've tried renaming the class and starting again is it possible that I have
a bug of some sort.

Thanks


Jon Skeet

unread,
Feb 11, 2002, 4:26:17 AM2/11/02
to

Catching ArrayIndexOutOfBoundsException seems an over-the-top way of
detecting this. If I need a certain number of arguments, usually the
first line will be something like:

if (args.length != 5)
{
System.err.println ("Usage: Foo <arg1> <arg2> ...");
System.exit (1);
}

(I sometimes use return instead of System.exit, to play nicer with other
Java code which runs main. I'm not terribly consistent on that one
yet...)

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Chris Sargent

unread,
Feb 11, 2002, 4:42:50 AM2/11/02
to
Output the number of argument to make sure you're actually passing
them to the application. i.e. System.out.println( "args=" +
args.length );
I suspect that the answer will be zero.

- sarge

0 new messages