Take values separated by spaces in Java

Asked

Viewed 7,264 times

4

Could someone explain to me how I can take 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 into a variable.

1 answer

12


You can separate using the method split() 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);
        }
    }
}

Upshot:

1
2
3

The split() will transform String into a array of strings, where the separation of the elements is given by the space found in the string text. PS: the space will not be part of any of the elements of array, it is considered only as delimiter of the elements and is discarded after the split().

The for (String s: arrayValores) is what is known as "for ", it traverses every element of the array and associates it with the variable s. It would be similar to do:

for (int i=0; i < arrayValores.length; i++) {
    String s = arrayValores[i];
    System.out.println(s);
}

But in a way that is written less to get the desired result.

  • Great answer, just one more thing, could you explain to me what you do and how this one works? I am a beginner, and had only come across for’s of this type "for (int i = 0; i > x; i++)".

  • I edited my answer, see if it helped.

  • Thank you took away my doubt.

Browser other questions tagged

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