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

5
  • 3
    What are the strings you pass in? Commented Jul 30, 2011 at 6: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. " download.oracle.com/javase/1.4.2/docs/api/java/lang/… Commented Jul 30, 2011 at 6:10
  • 3
    That happens when the string is not a properly formatted integer. Also, you should probably use int[] not Integer[]. Commented Jul 30, 2011 at 6: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 Commented Jul 30, 2011 at 6:44
  • Please copy/paste exception and error messages in future. You can edit your question to add those details. Commented Jul 30, 2011 at 6:54

9 Answers 9

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

Sign up to request clarification or add additional context in comments.

3 Comments

how to use same lambda expressions to convert string array to Integer object array?
@ffguven I feel autoboxing should take care of that whenever the need arises, or am I missing something?
@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);
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

Comments

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);

3 Comments

I would advise against your "code neatness" proposal - it makes the code more confusing, not more neat.
I find the "neater" code perfectly readable. Concise code can look quite nice. :)
@La-comadreja I do not. The non-neater method is more "natural".
8

Another short way:

int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();

Comments

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.

Comments

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.

}

}

Comments

1

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

Comments

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*/);

Comments

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.