Converting a String array into an int Array in java
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions[1] [2] (since Java 8), you can do the next ▼:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
▼ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start