Menu and input validation
Let’s switch back to the terminal now, and we can use control flow to create a small menu and to validate user input.
We can use the following starter code to get things going.
Creating a menu
At this point we have shown a menu to the user, and read in their choice. Now we need to add branches for the different paths we will need for these options. We could use a number of if statements, but for this we could use a switch
statement to provide the necessary branches.
Have a go at adding in a switch
stateemnt for the above code. For now, just output the name of the branch taken. So, for example, output “Addition” if the user chooses 1.
Looping until quit
With this menu we want the user to be able to perform multiple actions, so we need to repeat this until they choose to quit. Let’s do this by adding a do ... while
loop.
Have a go at embedding the code that shows the menu and performs its actions inside a do while loop. This can repeat while the user’s choice is not 5.
Compile and run the program and make sure that you can repeat the menu actions.
Validating input
Now try entering something other than a number. Something like “one”. The program will crash. Why, we attempted to convert this into a number. When the library cannot do this, it raises an error that causes the program to crash.
We can avoid this if we test the string before we try to convert it to a number. SplashKit provides an IsInteger function that will test if the string you pass it is an integer. There is also an IsDouble for testing if the values are valid doubles.
Have a think about how you could validate the user input. Will this be a branch or a loop?
-
Here we need to use a loop. This way we can require the user to provide us with a valid number. Without this we will not know which path to take in the menu. If you had used a branch, then the user may still enter an invalid number and the program will then crash when you attempt to convert this.
Compile and run the program. Test that it does not crash when you enter an invalid number. Try entering a few invalid entries, and see that the code handles this case as well.
With this, you have now seen how to use the basic control flow statements work. These are the foundation of every program.