Mario Mario - 6 months ago 12
Java Question

Converting String Array to an Integer Array

so basically user enters a sequence from an scanner input.

12, 3, 4
, etc.

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]
would be
12
,
int[1]
would be
3
, etc.

Any tips and ideas? I was thinking of implementing
if charat(i) == ','
get the previous number(s) and parse them together and apply it to the current available slot in the array. But I'm not quite sure how to code that.

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]);
}