Could someone explain to me how I can get values separated by spaces in Java?
For example, the user informs all at once the following values: 1 2 3
and I have to put each value in a variable.
Could someone explain to me how I can get values separated by spaces in Java?
For example, the user informs all at once the following values: 1 2 3
and I have to put each value in a variable.
You can sort by using the split()
method of the String class:
public class SplitString {
public static void main(String[] args) {
String valores = "1 2 3";
String[] arrayValores = valores.split(" ");
for (String s: arrayValores) {
System.out.println(s);
}
}
}
Result:
1
2
3
The split()
will transform the String into an array of Strings, and the separation of elements is given by the space that is found in the String text. PS: space will not be part of any of the array elements, it is considered only as a delimiter of elements and is discarded after split()
.
for (String s: arrayValores)
is what is known as " for
advanced", it traverses each element of the array and associates it with the variable s
. It would be similar to doing:
for (int i=0; i < arrayValores.length; i++) {
String s = arrayValores[i];
System.out.println(s);
}
But in a way that you write less to get the desired result.