Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

ArrayIndexOutOfBoundsException in Main method.

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me what is the best way to check for data passed to the main method in the args[0] parameter without causing this exception?
I want to be able to check for a parameter passed and if one does not exist I want to be able to assign a default value.
Thanks,
Brian
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally that is done with overloaded constructors.
In MyClass() (no parameters passed) set the default value yourself, then call MyClass(String s) (or whatever) using the default value you set.
this(s);
If a value is passed in the MyClass(String s) constructor will get called instead.
 
Brian Tomlin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Cindy,
I'll try that.
 
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the way I have been doing this for the cattle drive assignments:
if ( args.length > 0 )
// do something with args[0]
else
// assign your default value here
You could also change the test in the above if statement to ( args.length == 1 ) or whatever you need to check for exactly...
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also put it in a try / catch block and handle the exception.
 
Brian Tomlin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ryan, and Cindy.
Both are great suggestions. I have used args.length in the cattle drive assignments too, but I had forgotten about it. I guess I had a momentary lapse of reason. Thanks for the kick!
Brian
 
He baked a muffin that stole my car! And this tiny ad:
Try Free Java/.NET Libraries for Word Excel PowerPoint and PDF
htttp://www.e-iceblue.com/free-apis.html
    Bookmark Topic Watch Topic
  • New Topic