The continue statement skips the current iteration of a loop by bypassing any remaining statements in the loop body. The loop condition is then reevaluated, allowing the loop to potentially move onto the next iteration.
To calculate the sum of all positive integers in a list, you can use the continue statement to skip any negative integers:
Integer[] numbersToSum = new Integer[] {-5, 10, -2, -3, 6}; // Only 10 and 6 should be summed Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 16 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer i = 0; i < numbers.size(); i++){ if(numbers[i] < 0){ // skip this iteration if the element is less than zero continue; } sum += numbers[i]; } return sum; }
instead of using the continue statement, a more direct approach is to only perform the calculation sum += numbers[i];
on positive numbers:
Integer[] numbersToSum = new Integer[] {-5, 10, -2, -3, 6}; // Only 10 and 6 should be summed Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 16 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer i = 0; i < numbers.size(); i++){ if(numbers[i] > 0){ sum += numbers[i]; } return sum; }
or better yet, use a for each loop since the indices are not relevant:
Integer[] numbersToSum = new Integer[] {-5, 10, -2, -3, 6}; // Only 10 and 6 should be summed Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 16 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer num : numbers){ if(num > 0){ sum += num; } return sum; }
As you progress through your journey, I suggest that you form your own opinions about what you prefer.