-1

I am currently working on a program which performs several different functions, yet all on the same array (made up of the command-line arguments).

I am trying to create a function that will create an array. At the moment, I have to repeatedly put the following in each if statement of main() :

 final int N = args.length;    
 final long []a = new long [args.length];
 for (int i = 0; i < N; ++i) 
   a[i] = Long.parseLong (args[i]);

Surely I can put this in a function that I can call within a single line, rather than using this over and over again?

Any suggestions would be greatly appreciated!

0

3 Answers 3

1

You'll want to create a static function, so you are able to call it without creating a new instance of the object.

static long[] getValues(String[] args){
    long []a = new long [args.length];
    for (int i = 0; i < args.length; ++i) 
        a[i] = Long.parseLong (args[i]);
    return a;
}

void main(String[] args){
    long[] values = getValues(args); 
    //here you call the static function
    //do some code magic with those values
}
2
  • It would be great if you can add some texts and explain your code. In that way, more SO users can receive benefit. :)
    – jazzurro
    Dec 8, 2014 at 1:17
  • Sure. Let me try to explain Dec 8, 2014 at 1:45
1

Try:

public long[] methodName(String[] args){
    final int N = args.length;    
    final long[] a = new long [N];
    for (int i = 0; i < N; ++i) 
        a[i] = Long.parseLong (args[i]);
    return a;
}
-1

Use System.arraycopy(args, 0, a, 0, args.length);

See here

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.