Mario Mario - 1 year ago 77
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.

would be
would be
, 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 Source

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]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download