I am trying to take a string of numbers seperated by a singl

I am trying to take a string of numbers seperated by a single space and covert them into a string array. I have created the following code but it only works if the numbers are seperated a a comma or something similar to that.

Example of what I am trying to achieve:

string input = \"1 1 1 1 1\" turn it into.... int[] x = {1,1,1,1} so that it is printed as... [1, 1, 1, 1]   

This is the code I have so far....

public static void main(String[] args) {

       Scanner input = new Scanner(System.in);

       System.out.println(\"Welcome to the Guess The CodeGame!\");

       System.out.println(\"Please enter the code you want to use wiht a \' \' in between each number\");

       String x = input.next();

       String[] strArray = x.split(\",\"); // this only works with a comma, doesnt work with a x.split(\" \");

       int[] intArray = new int[strArray.length];

       for (int i = 0; i < strArray.length; i++) {

           intArray[i] = Integer.parseInt(strArray[i]);

           System.out.println(Arrays.toString(intArray));

       }

       System.out.println(Arrays.toString(intArray));

   }

Solution

Note:

The code you wrote every thing was right.But a small change.To read the String with spaces we have to use

nextLine() method of Scanner class Object.But you used next() method.That was the only change.

next() method of Scanner class is used to read the word.

nextLine() method of Scanner class is used to read the sentence with spaces.

____________________

StringToIntArray.java

import java.util.Arrays;
import java.util.Scanner;

public class StringToIntArray {

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
System.out.println(\"Welcome to the Guess The CodeGame!\");
System.out.println(\"Please enter the code you want to use with a \' \' in between each number\");
String x = input.nextLine();
String[] strArray = x.split(\" \"); // this only works with a comma, doesnt work with a x.split(\" \");
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);

}
System.out.println(Arrays.toString(intArray));

   }

}

_______________________

Output:

Welcome to the Guess The CodeGame!
Please enter the code you want to use with a \' \' in between each number
1 1 1 1 1 1 1
[1, 1, 1, 1, 1, 1, 1]

_____________Thank You

I am trying to take a string of numbers seperated by a single space and covert them into a string array. I have created the following code but it only works if
I am trying to take a string of numbers seperated by a single space and covert them into a string array. I have created the following code but it only works if

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site