Nested Conditional Statements
Not Started

The requirements keep coming through! They come back and tell you that school resources are tight for the football, dance, and art classes. They're limiting those classes to senior students who are in their 12th school year.

The requirements are updated to say:

If the student's schoolYear is 12:
If the student's hobby is football, then sign them up for football.
Otherwise, if the student's hobby is dance, then sign them up for dance.
Otherwise, If the student's hobby is art, then sign them up for art.
Otherwise, sign them up for music

Otherwise:
Sign them up for music


These conditions are now nested. We should only run the conditionals that check for a student's hobby if the student is in year 12. Say the Student class is updated to this:

public class Student { public String name; public String hobby public Integer schoolYear; }

We'll need to create nested conditionals. Let's not rush into it. Let's first get a conceptual view of a nested conditional:

public void someFunction(Integer x, Integer y){ if(x == 5){ if(y > 10){ somethingExciting(); } else { somethingKindaExciting(); } } else { somethingLessExciting(); }

Here y will only be evaluated if x is exactly 5. Otherwise, the entire nested block is skipped and the code jumps straight to the else condition which runs somethingLessExciting().

Let's bring this concept to signupBasedOnHobby:

public class StudentScheduleController { public void signupBasedOnHobby(Student s){ if(s.schoolYear == 12) { 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); } } else { musicSignUp(s); } } }

This can really start being hard on the eyes, that's why it's important to line up all the open-close parentheses.

As a bonus, we can refactor this a bit. We can break some of this logic up into another method called signupSeniors and call this method when we know a student is a senior:

public class StudentScheduleController { public void signupBasedOnHobby(Student s){ if(s.schoolYear == 12) { signupSeniors(s); } else { musicSignUp(s); } } private void signupSeniors(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); } } }

Opinions will vary, but we think this will be a little easier to read.

Challenge

This version of the setTestResult method includes an exception for grading.

If the automaticPass parameter (the second parameter) is true, the score won't be evaluated. Instead, testResult will be automatically set to "Passed."

Otherwise, the score will be checked. If the score is greater than 70, the testResult will be "Passed"; if not, it will be "Failed."