Search code examples
javalistmethodsadditionalternate

Java - method that add element then multiply every element in a list


can I please for a help in this exercise? I exhausted my knowledge, after many hours. I need to write a static method in Java that takes as a parameter list of numbers and returns int value. The value is a result of adding and multiplying alternate numbers in a list. As a addition I CANNOT use the modulo % to take odd or even index from loop.
How can I break the J inner loop, it is not incrementing when I use break, so j index is always 2. I am complete beginner.

As a example: [1, 2, 3, 4, 5] should be as a result: (1 + 2 * 3 + 4 * 5) = 27

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Exercise {
    static int addAndMultiply(List<Integer> list) {
        boolean flag = true;
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
                for (int j = 1; j < list.size(); j++) {
                if(flag) {
                    sum+= list.get(i) + list.get(j);
                    flag = false;

                }  else {
                    sum += list.get(i) * list.get(j);
                    flag = true;
                }
            } break;
        }
        return sum;
}
    public static void main(String[] args) {
        List<Integer> numbers = new LinkedList<>();
        Collections.addAll(numbers, 1, 2, 3, 4, 5);
        System.out.println(Exercise.addAndMultiply(numbers));
    }
}

Solution

  • You can do it this way :

    static int addAndMultiply(List<Integer> list) {
        int result = list.get(0);
        for (int i = 1 ; i < list.size() ; i = i+2) {
            if (i == list.size()-1) {
                result += list.get(i);
            } else {
                result += list.get(i) * list.get(i+1);
            }
        }
        return result;
    }