Link to home
Start Free TrialLog in
Avatar of shpark82
shpark82

asked on

program to accept parameters from command line

i'm trying to figure out how this is done in java...


in command, i would like to type in:

java -classpath \documents\location MyClass 1 2 3

which would add the three numbers following the class name.

MyClass is the class name

\documents\location is the class path

1 2 3 would be the parameters



please help
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can get them through the args parameters of main
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shpark82
shpark82

ASKER

how would i check if the args is int or string or float, etc?

for instance, if i put

1 12 123

as my parameters, would it recognize the numbers as

1,1,2,1,2,3?

or

1,12,123?

also what would happen if i put a letter such as 'A' in it for example

1 A 12

should i be checking if any of the args are not int and throw an exception?
The args are space-separated

>>should i be checking if any of the args are not int and throw an exception?

Yes, if that's a possibility
int sum = 0;
if(args.length > 0) {
      for(int i = 0;i < args.length;i++) {
            if (args[i].matches("\\d+")) {
                  sum += Integer.parseInt(args[i]);
            }
        
      }
}
System.out.println("Sum = " + sum);
> 1,12,123?

it would recognise it as 3 strings

> should i be checking if any of the args are not int and throw an exception?

the code I posted above will throw an exception if its not a number

   int param1 = Integer.parseInt(args[0]);
This would work for floating point numbers too. If you're interested in int/long, cast to int/long:


double sum = 0;
if(args.length > 0) {
      for(int i = 0;i < args.length;i++) {
            try {
                  sum += Double.parseDouble(args[i]);
            }
            catch(NumberFormatException e) {
                  e.printStackTrace();
            }
        
      }
}
System.out.println("Sum = " + sum);