Getting an input from command-line and passing it to a method
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[strA开发者_StackOverflow中文版rray.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);
}
}
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 variablestrArray[]
inStrArrtoIntArr
is a different variable in a different (local) scope. Keeping the global variable might be confusing.
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.
Damn beat me to the punch!
you forgot to store you array of ints as:
int[] intArray = array_convert.StrArrtoIntArr(args);
精彩评论