Mario - 8 months ago 17

Java Question

so basically user enters a sequence from an scanner input.

`12, 3, 4`

It can be of any length long and it has to be integers.

I want to convert the string input to an integer array.

so

`int[0]`

`12`

`int[1]`

`3`

Any tips and ideas? I was thinking of implementing

`if charat(i) == ','`

Answer

You could read the entire input line from scanner, then split the line by `,`

then you have a `String[]`

, parse each number into `int[]`

with index one to one matching...(assuming valid input and no `NumberFormatExceptions`

) like

```
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others
numbers[i] = Integer.parseInt(numberStrs[i]);
}
```