Control Flow Statements: continue
Not Started

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.

Challenge

Recall the StudentScheduleController class we looked at in the conditionals course:

public class StudentScheduleController { public void signupBasedOnHobby(Student s){ if(s.hobby == 'football'){ footballSignup(s); // Only call this line if the student's hobby is football } else if (s.hobby == 'dance'){ danceSignup(s); } else if (s.hobby == 'art'){ artSignup(s); } else { musicSignup(s); } } }

The handleRegistration() method in StudentController accepts a list of the Student datatype named students. Update this method so it calls the ssc.signupBasedOnHobby(student); statement only if the student's hobby is not blank.

Some students in the list will have hobbies and others will not. The size of the list will not be consistent.