Search code examples
javaloopsrandommodulusdigits

Need to sum digits in random numbers from loop


I'm randomly generating 3 digit numbers using java.util.Random(). The number of random 3-digit numbers that the system prints is controlled by user input. Here's the code:

//If/then statement for determining game type (determines 3 digit numbers)
if (gameType == 3) 

//for loop to generate random numbers (numGames is how many 3 digit numbers     to print)
for (int i = 1; i <=numGames; i = i + 1){

int ranNums = randomGenerator.nextInt((999 - 100) + 1) + 100; 

//Print random numbers to user
System.out.println(ranNums);

sumNums = ranNums % 10;

Basically, I want the code to add the DIGITS that are printed from the random number generator. For example, if the ranNums output is 111 and 111, I want the variable sumNums to equal 6, not 222. With the code I have now, it only adds the last digit of each number, (in this case 1 + 1 = 2).


Solution

  • You could do this:

    sumNums = (n / 100) + (n / 10 % 10) + (n % 10);