Happiness Meter

Line: Conditional Line
Medium Difficulty Selection Learning Outcome One Walkthrough
Type: Walkthrough
You should have completed: Try Parsing This topic leads to: ConsoleMenu

Summary

Another selection problem is where we have a number of possible values, and must choose one of a number of actions to perform based on that value. This is useful for choosing menu options, controlling 'finite state machines' and in many other ways.

In this exercise the user is asked to rate their current happiness on a scale of 1 to 5, the program will then offer some tongue-in-cheek advice based on that input.

Task

  1. Create a new console application
  2. Within "main" type in the following code
    code snippet
  3. Run the program and enter '1'
  4. Run the program and enter '2'
  5. Run the program and enter '3'
  6. Now add further code for the remaining 3 options
    1. '3' will advise the user to 'Think of puppies and kittens'
    2. '4' will advise the user to 'Go out and share their happiness with others'
    3. '5' will advise the user that 'they have reached a place of serenity and need do nothing to risk changing that'
  7. Run the program several times and enter a variety of numbers between 1 and 5.
  8. Ensure that your program is giving the correct advice

If...else if construction like this works, but is not as robust as the switch statement.

  1. Rewrite the above program to use a switch statement instead.

Questions

  1. When might it be impossible to use a switch statement instead of if...else if?