How to split a string and then convert to int?

3

I have a string "1 2 3 4 5" to split it and save the numbers into separate variables I was reading and saw that it has to use a method called Split ... I tried to do but I could not.

How do I do this, and then how do I convert to int the results so that I can eg add up all the numbers ?? In short: I want to know how to convert an integer String to an int array. The code that gave error was this:

public class Main {
public static void main(String[] args) {
    String x = ("1 2 3 4 5");
    String array[] = new String[5];
    int resultado[] = new String[5];
    array = x.split (" ");
            System.out.println(resultado[0]+resultado[1]+resultado[2]+resultado[3]+resultado[4]);
}

}

    
asked by anonymous 03.08.2015 / 03:00

1 answer

6

Some considerations regarding your code:

  • You do not need to declare and instantiate a vector to get the Split return. Split itself already instantiates and returns an array of type String for you. So you just need the statement.

    String array[] = x.split (" ");

  • You are trying to assign a vector of type int (result []) to a vector of type String. This will give compilation error, since java is a strongly typed language.

  • To perform the conversion you can use the following approach, see:

    int resultado[] = new int[5]; for(int i = 0; i < 5; i++) { resultado[i] = Integer.parseInt(array[i]); }

  • The above code used the parseInt static method of the Integer class to convert a String to an Integer.

        
    04.08.2015 / 03:03