Home > Back-end >  Counting sum of numbers in a for loop
Counting sum of numbers in a for loop

Time:12-13

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;
    
    for (int i=0; i<=100; i  ) {
        rndmNum=1 rndm.nextInt(9);
        rNums.add(rndmNum);
        sum =i;
        if (sum>=100) {
            break;
        }
    }
    
    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!

CodePudding user response:

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 by using this code:

public static void main(String[] args) {
    ArrayList <Integer> rNums=new ArrayList<>();
    int rndmNum=0;
    Random rndm=new Random();
    int sum=0;

    for (int i=0; i<=100; i  ) {
        rndmNum=1 rndm.nextInt(9);
        rNums.add(rndmNum);
        sum  = rndmNum;
        if (sum>=100) {
            System.out.println(i   1);
            break;
        }
    }

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

CodePudding user response:

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);
    }
  •  Tags:  
  • java
  • Related