How do I split a string of ints at every space
A project I'm doing for school requires me to get a user input of a a set of ints. The way the will be inputted is like this; "1 4 2 5 345 6 3 234". I need to split them every space and into an array. I've tried doing .split(" ") but that does not seem to yield any results unless I input characters instead of numbers.
Here's what I have:
Code:
Scanner input = new Scanner(System.in);
String votes = input.next();
String[] array = votes.split(" ");
The array is currently just storing the first number that was inputted and none of the other ones
Re: How do I split a string of ints at every space
Re: How do I split a string of ints at every space
Awesome, thanks! That seems to have solved it!
Re: How do I split a string of ints at every space
Also, I think you want to split on "\\s+" instead of a single space.
kind regards,
Jos
Re: How do I split a string of ints at every space
Thanks! In the Googleing I did to look for an answer I saw most of the examples included that. Should help eliminate any input errors, even though they tell us what they will be inputting into our code to test it.
Re: How do I split a string of ints at every space
Quote:
Originally Posted by
josho493
Thanks! In the Googleing I did to look for an answer I saw most of the examples included that. Should help eliminate any input errors, even though they tell us what they will be inputting into our code to test it.
Splitting on "\\s+" splits the String one one or more spaces (any white space) so any input with just one space between the numbers will be split correctly while the code will be more robust.
kind regards,
Jos
Re: How do I split a string of ints at every space