Get values separated by spaces in Java

4

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.

    
asked by anonymous 23.06.2015 / 16:11

1 answer

12

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.

    
23.06.2015 / 16:15