We're not quitting on this scheduling example just yet. The school has decided they can't support everyone's hobby. So any students whose hobby is not football, dance, or art should be signed up for music.
The requirements are updated to say:
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.
We can represent this type of logic with the if-else
conditional. Here's a conceptual view of a basic if-else
conditional:
public void someFunction(Integer x){ if(x == 5){ somethingExciting(); } else { somethingLessExciting(); } }
When x
is passed in, the first conditional will check if it is exactly equal to 5. If so somethingExciting
will execute. Otherwise, if it's greater than 5 or less than 5, somethingLessExciting()
will execute.
This is very different from this:
public void someFunction(Integer x){ if(x == 5){ somethingExciting(); } somethingLessExciting(); }
In this version, regardless of x
's value, somethingLessExciting()
will always run.
The else
statement can be combined with either an if-statement
or an if-else
statement. So let's apply this concept to signupBasedOnHobby
:
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); } } }
There we go! If a student's hobby is not football, dance, or art then they'll be signed up for music.