Java Reference
In-Depth Information
16 product *= n;
17 }
18 System.out.println("product = " + product);
19 }
20 }
The program produces the following output:
list = [13, 4, 85, 13, 40, -8, 17, -5]
product = 1562912000
Here is a variation that removes any 0 values from the list, computing the product
of the nonzero values:
1 public class Client3 {
2 public static void main(String[] args) {
3 // construct and print list
4 int [] data = {5, 19, 0, 2, 4, 0, 13, 85, -8, 0, 23};
5 ArrayIntList list = new ArrayIntList();
6 for ( int n : data) {
7 list.add(n);
8 }
9 System.out.println("list = " + list);
10
11 // use an iterator to find the product, removing zeros
12 ArrayIntListIterator i = list.iterator();
13 int product = 1;
14 while (i.hasNext()) {
15 int n = i.next();
16 if (n == 0) {
17 i.remove();
18 } else {
19 product *= n;
20 }
21 }
22 System.out.println("list now = " + list);
23 System.out.println("product = " + product);
24 }
25 }
The program produces the following output:
list = [5, 19, 0, 2, 4, 0, 13, 85, -8, 0, 23]
list now = [5, 19, 2, 4, 13, 85, -8, 23]
product = -154523200
Search WWH ::




Custom Search