Reputation: 2001
I am loading a String from a csv file and trying to make an int array with it. The problem is I keep running into a NumberFormatException
which is thrown when the program finds a ""
in the String array.
I don't need those empty Strings, I just want ints.
Is there a way to avoid replacing characters with empty Strings?
aLine = aLine.replaceAll(" ", "").replaceFirst(",", "");
aLine = aLine.replace(name, "").replaceAll("\"", "");
final String[] strScores = aLine.split(",");
final int[] scores = Arrays.stream(strScores)
.mapToInt(Integer::parseInt).toArray();
Upvotes: 0
Views: 69
Reputation: 64
You should use an array list because you can easily add and remove
array_list<String> list = new ArrayList<String>(); // create array list
for (int i =0; i < array_string.length;i++){
if (!string_array[i].equals("")){ // filter out empty
array_list.add(string_array[i]);
}
}
String new_string_array_without_empty = array_list.toArray(new String[0]); // convert to string array again
Upvotes: 0
Reputation: 201507
You could filter
the stream for not empty and not null
before you parse
. Like,
final int[] scores = Arrays.stream(strScores)
.filter(x -> x != null && !x.isEmpty())
.mapToInt(Integer::parseInt)
.toArray();
Upvotes: 2