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

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
Manoj I
  • 1,089
  • 1
  • 13
  • 18
  • 3
    What are the strings you pass in? – BoltClock Jul 30 '11 at 06:10
  • 1
    "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. " http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String) – Dan Grossman Jul 30 '11 at 06:10
  • 3
    That happens when the string is not a properly formatted integer. Also, you should probably use `int[]` not `Integer[]`. – Mike Samuel Jul 30 '11 at 06:10
  • 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 Thanks – Manoj I Jul 30 '11 at 06:44
  • Please copy/paste exception and error messages in future. You can edit your question to add those details. – Andrew Thompson Jul 30 '11 at 06:54

9 Answers9

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

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • 2
    how to use same lambda expressions to convert string array to Integer object array? – ffguven Mar 08 '18 at 11:36
  • @ffguven I feel autoboxing should take care of that whenever the need arises, or am I missing something? – Ayush Aug 31 '20 at 09:09
  • 1
    @ffguven 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);` – Ayush Jun 29 '21 at 12:21
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
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
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);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
8

Another short way:

int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
J. Doe
  • 12,159
  • 9
  • 60
  • 114
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.

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
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);
    }
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Deepak
  • 49
  • 2
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.

}

}

Aditya
  • 11
  • 1
  • 1
  • 6
1

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

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*/);
Bram Van Dyck
  • 109
  • 10