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]);
}
}
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.
– Maniero
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?– mgibsonbr
Best option uses split and plays in and an array these values later just work with it.
– Wellington Avelino
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...
– pedrocarboni