current position:Home>Using random class, randomly generate five integers between 1 and 100, add the generated random integers to a list set, and then calculate the sum of all numbers in the set

Using random class, randomly generate five integers between 1 and 100, add the generated random integers to a list set, and then calculate the sum of all numbers in the set

2022-02-02 21:06:17 CSDN Q & A

utilize Random class , Random generation 5 individual 1 To 100 Integer between , Add the generated random integer to a list Collection , Then calculate the sum of all the numbers in the set




Refer to the answer 1:
import java.util.Random;public class Test{  public static void main(String[] args){        Random rnd = new Random();        int a[] = new int [5];        List<Integer> list = new ArrayList<Integer>();        for(int i=0;i<5;i++)            list.add(rnd.nextInt(100)+1);        int sum = 0;        for(int n :list){            sum += n;        }        System.out.print("sum="+sum);    }}



Refer to the answer 2:



Refer to the answer 3:

Traversal implementation




Refer to the answer 4:



Refer to the answer 5:

The sample code is as follows :

public class Test {    public static void main(String[] args) throws SQLException, IOException {        int sum = Arrays.stream(new int[5]).map(item -> new Random().nextInt(100) + 1).sum();        System.out.println(sum);    }    }



Refer to the answer 6:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202022106150059.html

Random recommended