I am new to java programming. My question is this I have a String
array but when I am trying to convert it to an int
array I keep getting
java.lang.NumberFormatException
My code is
private void processLine(String[] strings) { Integer[] intarray=new Integer[strings.length]; int i=0; for(String str:strings){ intarray[i]=Integer.parseInt(str);//Exception in this line i++; } }
Any help would be great thanks!!!
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
Using toArray() MethodThe toArray() function of the List class can also be used to convert a string to array in Java. It takes a list of type String as the input and converts each entity into a string array.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With