Parsing many Ints from a user input String.
I'm writing a java program that takes an input from a user as a string. Then has to take that random string and parse all of the ints in order and put them into an array. I have to have a method with the only input as the string that returns the int array, which is where I'm having trouble.
In the method I have a string array set up first to the length of the array. And I have a counter. I have a for loop that has (int a = 0; a <= string.length; a++) I check if charAt(a) = a number, if so I make stringArray[count] = stringArray[count]+charAt(a), if not i check if a = 0, and if so do nothing, last I check if the charAt(a-1) is a number, if so I increase the counter. After I have the string array completed I make my int array with length of my counter then I have a for loop one more time that has (int b = 0; b <= cnt; b++) and for intArray[b] I parseInt StringArray[b]. what am I doing wrong it keeps giving me errors like stringindex out of bounds or numberformat exception.
Here is my method code;
public static int[] intParse(String s)
{
String[] placeKeeper = new String[s.length()];
for (int a = 0; a < s.length(); a++)
{
placeKeeper[a] = "";
}
int cnt = 0;
for (int a = 0; a <= s.length(); a++)
{
if (s.charAt(a) == '1' || s.charAt(a) == '2' || s.charAt(a) == '3' || s.charAt(a) == '4' || s.charAt(a) == '5' || s.charAt(a) == '6' || s.charAt(a) == '7' || s.charAt(a) == '8' || s.charAt(a) == '9' || s.charAt(a) == '0')
{
placeKeeper[cnt] = placeKeeper[cnt] + s.charAt(a);
}
else if (a == 0)
{
}
else if (s.charAt(a-1) == '1' || s.charAt(a-1) == '2' || s.charAt(a-1) == '3' || s.charAt(a-1) == '4' || s.charAt(a-1) == '5' || s.charAt(a-1) == '6' || s.charAt(a-1) == '7' || s.charAt(a-1) == '8' || s.charAt(a-1) == '9' || s.charAt(a-1) == '0')
{
cnt ++;
}
} //end for loop
int[] array = new int[cnt];
for (int b = 0; b <= cnt; b++)
{
array[b] = Integer.parseInt(placeKeeper[b]);
}
return array;
}
Re: Parsing many Ints from a user input String.
I'm not quite sure what your goal is, the original goal seems to just turn a string of numbers into an array of ints. The code you provided looks like you are counting frequency.
I'd suggest you look at using split and integer.parseInt to trivialize the process.