I have an integer, lottoNum generated from the java utility Random. I need to store the integer value of int lottoNum in an integer array called sumArray, so I can iterate through the array to add the value of each number. If lottoNum = 123456, the integer array should be sumArray[] = {1, 2, 3, 4, 5, 6}; I'm not sure how to do this and hope I can get some help.
This is my code for the int lottoNum
// generate sets of random numbers between 1-9
randNum = genNumbers.nextInt(10);
// store the numbers into lottoNum
lottoNum = (lottoNum * 10) + randNum;
lottoNum gets passed into another class where the math is supposed to be performed, then returned as sum.
This is my code to iterate through the array to add the numbers up
public int doMath(lottoNum) {
int sumArray[] = {};
int sum = 0;
for (int i : sumArray)
sum += i;
return sum;
}
How (or can I) place the value of lottoNum into the {} of the array? I was reading something about splitting the numbers in lottoNum, but I'm completely lost on this.
I also found this code to get separate digits of an integer, but an not sure how to put the output into the array.
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
Help is greatly appreciated.
1 Answer 1
The result will be in arr
, and will be in the reversed order of the digits in the original number. Say number is 123, and the result array will be {3, 2, 1}.
int number; // = some int
List<Integer> arrList = new ArrayList<>();
while (number > 0) {
// To keep the same order, use arrList.add(0, number % 10);
arrList.add(number % 10);
number = number / 10;
}
Integer[] arr = new Integer[arrList.size()];
arrList.toArray(arr);
or you can convert the number to string and then convert each character to a digit;
int number; // some number
char[] numChars = Integer.toString(number).toCharArray();
int arr[] = new int[numChars.length];
for (int i = 0; i < numChars.length; ++i) {
arr[i] = numChars[i] - '0';
}
-
Thank you so much for your help! I'm incorporating this in the code now and will report back. I greatly appreciate you taking your time to help me with, what appears to be, such a basic question.Cannoli– Cannoli2016年04月10日 19:21:51 +00:00Commented Apr 10, 2016 at 19:21
lottoNum % 10
in a loop to get the values in the ones position.