I am assuming you are asking the user to input a sequence of numbers in a single line. So you might get 1 , 2 3 , 52
as the inputted value as a string. You want to store the numbers into an int
array.
A way to do this is take the string and remove all characters that have nothing to do with the numbers, in this case it are spaces and komma's. There would be a problem if someone enters a 1 , 4 59
, but i am ignoring that scenario because it has nothing to do with the question.
String line = scanner.nextLine(); // line = "1 , 2 3 , 45"
Remove the komma's first:
String result = line.replaceAll("," , " "); // replaces all komma's with a space.
Now you have a string with no komma's
To avoid double digit numbers to be converted into 2 single digits, you can use a StringTokenizer
.
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints out:
this
is
a
test
We can use this to remove the whitespaces between the numbers in our string or actually only use the values that are read as tokens.
StringTokenizer resultLine = new StringTokenizer(result);
int[] numbers = new int[resultLine.countTokens()];
for (int i = 0; resultLine.hasMoreTokens(); i++) {
numbers[i] = Integer.parseInt((String) resultLine.nextElement());
}
for (int j = 0; j < numbers.length; j++) {
System.out.print(numbers[j] + " ");
}
System.out.println();
}
Which finally gets us the result we want, an array of integers.
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String line = s.nextLine();
String result = line.replaceAll(",", " ");
StringTokenizer resultLine = new StringTokenizer(result);
int[] numbers = new int[resultLine.countTokens()];
for (int i = 0; resultLine.hasMoreTokens(); i++) {
numbers[i] = Integer.parseInt((String) resultLine.nextElement());
}
for (int j = 0; j < numbers.length; j++) {
System.out.print(numbers[j] + " ");
}
System.out.println();
}
Input was: 1 , 2 3 , 52
Output is: 1 2 3 52 // int[] numbers = {1,2,3,52};
I hope this is of some use to you.