I want to convert String lotto int an integer array. String lotto is composed of a certain amount of numbers between 1 and 99 and is only composed of 1 and 2 digit numbers. (Example: String lotto might look like "1 34 5 23 7 89 32 4 10 3 6 5".)
I am trying to solve the problem by converting the String to char[] and then the char[] to an int[]. My logical behind converting it to the char[] is make it possible to format the numbers for the int[].
Here is what I have so far:
public static int[] conversion(String lotto)
{
char[] c = lotto.toCharArray();
int[] a = new int[c.length];
for(int i = 0, j = 0; i < c.length; i++)
{
if(c[i] != ' ' && c[i+1] != ' ')
{
a[j] = c[i] + c[i+1];
i+=2;
j++;
}
else if(c[i] != ' ' && c[i+1] == ' ')
{
a[j] = c[i];
i++;
j++;
}
}
return a;
}//end of conversion method
I am still working on the rest of the program but I know that c[i] + c[i+1] with return an ASCII value or a different int rather than combining the two chars together (Example of what I want: '3' + '4' = 34.)
How do I fix this problem?
If you don't care about converting to a character array then you could just use the .split() method
String[] nums = lotto.split(" ");
int[] a = new int[nums.length];
for(int i = 0; i < a.length; i++)
{
a[i] = Integer.parseInt(nums[i]);
}
return a;
Try using String.split
String numbers[] = lotto.split (" ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With