Converting a String array into an int Array in java
Asked Answered
E

9

45

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!!!

Excitability answered 30/7, 2011 at 6:8 Comment(5)
What are the strings you pass in?Iconology
"The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method. " download.oracle.com/javase/1.4.2/docs/api/java/lang/…Contortionist
That happens when the string is not a properly formatted integer. Also, you should probably use int[] not Integer[].Ockham
Hi Found the error there was a trailing "\r" in the string array.so 3 was taken as "3\r".I removed the trailing \r and it worked ThanksExcitability
Please copy/paste exception and error messages in future. You can edit your question to add those details.Hindi
A
23

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
Andriette answered 30/7, 2011 at 23:16 Comment(0)
M
116

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

Montsaintmichel answered 2/10, 2014 at 15:23 Comment(3)
how to use same lambda expressions to convert string array to Integer object array?Earthman
@Earthman I feel autoboxing should take care of that whenever the need arises, or am I missing something?Cyprinodont
@Earthman okay one year later, I stumble upon the same thread, I look at my previous comment and realise I was actually missing something. One way(idk if it's the best way) to do so would be : Integer[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);Cyprinodont
A
23

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
Andriette answered 30/7, 2011 at 23:16 Comment(0)
A
12

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);
Absorbance answered 30/7, 2011 at 23:21 Comment(3)
I would advise against your "code neatness" proposal - it makes the code more confusing, not more neat.Kayser
I find the "neater" code perfectly readable. Concise code can look quite nice. :)Imperative
@Imperative I do not. The non-neater method is more "natural".Worldling
C
8

Another short way:

int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Colbert answered 12/10, 2018 at 7:39 Comment(0)
C
2

Since you are trying to get an Integer[] array you could use:

Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

Your code:

private void processLine(String[] strings) {
    Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}

Note, that this only works for Java 8 and higher.

Cavatina answered 8/6, 2020 at 15:55 Comment(0)
I
1
private void processLine(String[] strings) {
    Integer[] intarray=new Integer[strings.length];
    for(int i=0;i<strings.length;i++) {
        intarray[i]=Integer.parseInt(strings[i]);
    }
    for(Integer temp:intarray) {
        System.out.println("convert int array from String"+temp);
    }
}
Inveracity answered 30/9, 2013 at 14:35 Comment(0)
D
1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class array_test {

public static void main(String args[]) throws IOException{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();

String[] s_array = line.split(" ");

/* Splitting the array of number separated by space into string array.*/

Integer [] a = new Integer[s_array.length];

/Creating the int array of size equals to string array./

    for(int i =0; i<a.length;i++)
    {
        a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int

        System.out.println(a[i]);
    }

    // your integer array is ready to use.

}

}

Diverticulitis answered 18/12, 2015 at 12:31 Comment(0)
W
1

This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.

Wariness answered 1/6, 2016 at 18:10 Comment(0)
F
1
public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
Fairfield answered 25/4, 2017 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.