views:

54

answers:

3

I'm getting a string array from command line and displaying it to user as integer array. What could be the mistake here?

import java.lang.String;

public class arrayConvert {

    String strArray[];

    public int[] StrArrtoIntArr(String strArray[])
    {
        int intArray[] = new int[strArray.length];

        for(int count=0;count<strArray.length;count++)
        {
            intArray[count] = Integer.parseInt(strArray[count]);
        }

        return intArray;
    }

    public void displayArray(int intArray [])
    {
        for(int j=0;j<intArray.length; j++)
        {
            System.out.println(intArray[j]);
        }
    }

    public static void main(String[] args)
    {
        arrayConvert array_convert = new arrayConvert();
        array_convert.StrArrtoIntArr(args);
        array_convert.displayArray(intArray);
    }

}
A: 

Hand-written code for parsing command-line arguments is unnecessary and tedious, especially when you need to do extensive parsing. Use a 3rd-party library instead, like Apache Commons CLI.

skaffman
Is that relevant in this particular case ?
Brian Agnew
@skaffman Ok. I will check that
Sandeep
@Brian: It's relevant if he's wasting time parsing command-line arguments, when he could be spending that time solving real problems.
skaffman
+5  A: 

You forgot to save the intermediate result in you main class:

public static void main(String[] args)
{
    arrayConvert array_convert = new arrayConvert();
    int[] intArray = array_convert.StrArrtoIntArr(args);
    array_convert.displayArray(intArray);
}

There are some more things in your code, you might want to look at:

  • import java.lang.String; You don't need to include this. java.lang is automatically imported.
  • String strArray[]; This variable is never used. The variable strArray[] in StrArrtoIntArr is a different variable in a different (local) scope. Keeping the global variable might be confusing.
Scharrels
Oh ya! I saved the intermediate results and yet I get the error as I typed above.
Sandeep
You're right. I guess that's not the entire program. That was just step one and I had that global variable in mind for a different purpose. Anyways great observation Scharrels :)
Sandeep
A: 

Damn beat me to the punch!

you forgot to store you array of ints as:

int[] intArray = array_convert.StrArrtoIntArr(args);
Brendan
Thank you Brendan. Got the result. That was so silly of me of not saving the intermediate result. Happens with me atleast :)
Sandeep
Happens to the best of us. Just read through your code when your stuck, and you should figure it out. Believe me, I've done stupider things...
Brendan