• Post Reply Bookmark Topic Watch Topic
  • New Topic

Command line argument confusion  RSS feed

 
Clare Wright
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Hoping someone can point me in the right direction.

I have a Person class with comparators for each attribute of the person, so that I can sort according to the different attributes such as name, surname, age. At the moment when I type java TestPerson.java - it�s printing out something like:

Firstname sort:

Susan, Smith 25
Tom, Robbins 42

I now want to include in my command line argument the attribute and the type of sort Eg. TestPerson.java surname ascend. Are there any tutorials that would explain to me how programs take in command-line arguments?

Thanks, hugely appreciated.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it's not that hard - you've already done most of it.

in your declaration of main, you have this:



or something like that. that "args" string array holds all the parameters from the command line, using a space as the separator.

what you need to to is check that array for a size (to see how many, if any args were passed in), then process them however you see fit.
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your main method takes one argument, a String array, which are the command line args.

Example:

class TestPerson
{
public static void main(String[] args)
{
System.out.println(args[0]);
System.out.println(args[1]);
}
}

> java TestPerson.java surname ascend

results in:

surname
ascend


General Java 1.5 Tutorial
http://java.sun.com/docs/books/tutorial/index.html

General Java 1.5 Tutorial (main method explained)
http://java.sun.com/docs/books/tutorial/getStarted/application/main.html
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Command line arguments are simply elements in main's String array (which is usually called "args" or "argv"). If you don't specify any command line arguments, then args is empty with a length of zero. But if you type...

java TestPerson surnameAscend

...then args[0] will be "surnameAscend".

Note that arguments are separated by spaces. So if you type...

java TestPerson surname ascend

...then args[0] will be "surname" and args[1] will be "ascend".

See what you can do with this.
 
Clare Wright
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeehah! Awesome - thanks so much, I just got it working. You guys are the best.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!