Jake Xia Jake Xia - 7 months ago 13
Java Question

How do I get each number a user inputs as set of numbers in string with each number separated by a space?

For example, the user enters "1 2 3 4", how do I extract those four numbers and put them into separate spots in an array?

I'm just a beginner so please excuse my lack of knowledge.

for (int i = 0; i < students; i++) {
scanner.nextLine();
tempScores[i] = scanner.nextLine();

tempScores[i] = tempScores[i] + " ";
tempNum = "";
int scoreCount = 0;

for (int a = 0; a < tempScores[i].length(); a++) {
System.out.println("Scorecount " + scoreCount + " a " + a );

if (tempScores[i].charAt(a) != ' ') {
tempNum = tempNum + tempScores[i].charAt(a);
} else if (tempScores[i].charAt(a) == ' ') {
scores[scoreCount] = Integer.valueOf(tempNum);
tempNum = "";
scoreCount ++;
}
}

Answer

You can use String.split(String) which takes a regular expression, \\s+ matches one or more white space characters. Then you can use Integer.parseInt(String) to parse the String(s) to int(s). Finally, you can use Arrays.toString(int[]) to display your int[]. Something like

String line = "1 2 3 4";
String[] tokens = line.split("\\s+");
int[] values = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
    values[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(values));

Outputs

[1, 2, 3, 4]