Singh is Bling
Singh is Bling

Reputation: 7

Counting sum of numbers in a for loop

import java.util.Random;

public class RandomNumbers {

    public static void main(String[] args) {
    ArrayList <Integer> rNums=new ArrayList<>();
    int rndmNum=0;
    Random rndm=new Random();
    int sum=0;
    
    do {
        rndmNum = 1+rndm.nextInt(9);
        rNums.add(rndmNum);
        sum += rndmNum;
    } while (sum <= 100);
    }
    
    System.out.println(sum);
    System.out.println(rNums);
        
    }

}

Hi, I am trying to make it so that this loop counts the sum of all random numbers generated, and when the sum reaches 100 it stops and prints the sum, I could use some help!

Upvotes: 0

Views: 795

Answers (2)

Aniketh Malyala
Aniketh Malyala

Reputation: 2660

Instead of doing:

sum += i;

You should do:

sum += rndmNum;

Your original code sums up the iterator, i while the loop is still running, while it should be summing up all the values of rndmNum.

Let me know if you have any other questions!

Edit: You can output the amount of numbers generated and how many of each by using this code:

class Main {
  public static void main(String[] args) {
    ArrayList <Integer> rNums=new ArrayList<>();
    int rndmNum=0;
    Random rndm=new Random();
    int sum=0;
    int[] diffNums = new int[10];
    for (int i=0; i<=100; i++) {
        rndmNum=1+rndm.nextInt(9);
        rNums.add(rndmNum);
        diffNums[rndmNum]++;
        sum += rndmNum;
        if (sum>=100) {
            System.out.println(i + 1);
            break;
        }
    }

    System.out.println(sum);
    System.out.println(rNums);
    for(int i = 0; i < 10; i++){
      System.out.println(i + ": " + diffNums[i] + " times ");
    }
  }
}

Upvotes: 1

vaibhav shanker
vaibhav shanker

Reputation: 173

It will be better to do...while loop in such a problem.

      public static void main(String... ar) {
        ArrayList<Integer> rNums = new ArrayList<>();
        int rndmNum = 0;
        Random rndm = new Random();
        int sum = 0;
        do {
            rndmNum = rndm.nextInt(9);
            rNums.add(rndmNum);
            sum += rndmNum;
        } while (sum <= 100);

        System.out.println(sum);
        rNums.forEach(System.out::println);
    }

Upvotes: 0

Related Questions