How to split a string`and then convert to int?

Asked

Viewed 1,949 times

4

I have a string "1 2 3 4 5" to divide it and save the numbers in separate variables I was reading and saw that have to use a method called Split... I tried to do it, but I couldn’t.

How do I do this, and then how do I convert the results to int so that I can for example add up all the numbers?? Summarizing: I want to know how to convert an entire String array into 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]);
}

}

  • 15

    Show what you have done and we can tell you more easily where you are going wrong. This is the best help we can give. If we deliver ready, we’re not helping, we’re doing it for you.

  • 4

    Probably "store in separate variables" is not quite what you want. If the string comes with 10 numbers you will save in 10 variables? If it comes with 100 numbers, 100 variables? How will you write code to access these variables later? Etc. The method String.split in fact it is what you need (if that is the purpose of the question, I suggest [Dit] it clarifying this, then we can explain its operation better). You already know how to work with arrays?

  • Best option uses split and plays in and an array these values later just work with it.

  • So, I already know how to work with arrays, and that’s what I was using in the program. I can use Split, but then I can’t convert it to int...

1 answer

6


Some considerations regarding your code:

  1. You do not need to declare and instantiate a vector to receive the return of Split. Split itself already instance and returns an array of type String to you. Therefore, you only need the statement.

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

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

  3. 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 static method parseint class Integer to convert a String to an Integer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.