Let’s do it in parts
-
Generate random numbers. You are generating from
a = 1toa = 49random numbers insted of 50. If you know how many times you want to iterate, you may use theforloop. -
Math.random()returns a double, so you have to cast to int with(int)before it. See documentation here -
In
calculateTotal()you are iterating overnumbersbut you are not adding tototal, so the value oftotalwould be the last element ofnumbers. Also you have to initialize the variabletotalto 0, otherwise you will get an error. -
I add an extra function to calculate the total with lambda and streams included in Java 8. The
Integer::intValuecalls the method by reference.
public class MyClass {
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args) {
// Generate 50 different prices
for (int i = 0; i < 50; i++) {
int num = (int) (Math.random() * 100 + 1); // Add casting
numbers.add(num);
}
System.out.println(calculateTotal());
System.out.println(calculateTotalJava8());
}
public static int calculateTotal() {
int total = 0; // Initialize to 0
for (Integer price : numbers) {
total += price; // Add the price to the total
}
return total;
}
public static int calculateTotalJava8() {
int total = numbers.stream().mapToInt(Integer::intValue).sum();
return total;
}
}
0
solved I can’t get the sum of the list [closed]