Good morning all,

Hopefully a quick solution, I've done some reading up on taking command line
arguments and I almost have it licked, but I'm running into some trouble trying to
send into a method..

I'll give you an example of what I mean

Let's say I want to send 2 command line args into the program
the first argument args[0] will be a CHAR to select the method
and the second arguments args[1] would be the input data to run that method

How can I send args[1] into the methods (the methods being an int,double & string for required input) ?

I get an error if i call the method and try to directly send args[1]
I somehow need to parse the value first or something,

Am I close? :)

Help is always appreciated!

public static void main(String[] args) 
    {
    
	if(args.length==2)
	{
		if(args[0].charAt(0) == 'a')
		{
			intMethod();
			System.exit(0);
		}
		else if(args[0].charAt(0) == 'b')
		{
			doubleMethod();
			System.exit(0);
		}
		else if(args[0].charAt(0) == 'c')
		{
			stringMethod();
			System.exit(0);
		}
	}
    }

well .. you have String values of your input in your String args.
so, considering you calling methods in the same class as your main method, I would assume you have two possible solutions:

1. you create a couple of static class variables, in which you store the values you get from your command line args. Since these would be class variables, they would be accessible in your static methods.
2. you pass your variables as parameters to your methods, so they will automatically be accessible in these methods. I would suggest to take this approach.

Pass the String args[1] as a parameter to the method, and parse it as int or double if needed. Alternatively, you could parse it as int or double if needed and then pass the result to the method. The latter is nice because it allows you to detect bad input early on and just bug out with an error message.

if (args[0].charAt(0) == 'a')
{
  try {
    intMethod{Integer.parseInt(args[1]);
  }
  catch (NumberFormatException nfe)
  {
     System.out.println("Expected integer, got "+args[1]);
  }
}

and so forth...

Unfortunately, there's no way to test whether a String can be parsed as a number without trying it, so you're going to generate an exception on bad input. This is a reasonable way to handle that.

Now I don't know what happens after this, but you'll probably want to include some logic to continue correctly depending on whether the input was good and the method called or not - this is left as an exercise. :)

Wonderful, thank you both very much.
I should have realised that I needed to parseInt / parseDouble before sending them
to the methods, when you look at code too closely you can't see anything!

Solved and thanks again!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.