Validating Input
Our code works well if the user's input is right and valid. But, user could do anything right? They can input randomly in our code. Therefore, We need to validate the input.
If the input is 0 or negative minutes number
We could use if-else
in conditions minutes <= 0
, but it still runs the whole code. We need to start the code again when input is invalid. The trick is in continue
statement.
if (minutes <= 0)
{
Console.Write("Not a desired input");
continue;
}
Using continue
, the loop will starts again from the top, so it will not print the total minutes at the bottom of code.
If the input is not an integer
We could use if-else
statement again. But we want to show you another method called try-catch
.
Try-catch
statement will try to execute the code, but if the code is not able to run, we catch the exception shown.
What is the exception in our FitnessFrog?
The basic structure of try-catch
shown below.
try{
}
catch (Exception)
{
}
We would like to validating the input other than "quit", so we could perform try-catch
like code below.
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
string entry;
bool keepGoing = true;
int totalWorkingTime = 0;
while (keepGoing){
// Prompt the for minutes exercised
Console.WriteLine("Enter how many minutes you exercised: ");
entry = Console.ReadLine();
if (entry == "quit")
{
keepGoing = false;
}
else
{
try()
{
int minutes = int.Parse(entry);
if (minutes <= 0)
{
Console.Write("Not a desired input");
continue;
}
else if (minutes <= 10)
{
Console.WriteLine("Better than nothing, am I right?");
}
else if (minutes <= 30)
{
Console.WriteLine("Press your limit!");
}
else if (minutes <= 60)
{
Console.WriteLine("You must be an Indonesia ninja warrior");
}
else
{
Console.WriteLine("Okay, now you're just showing off!");
}
}
catch(FormatException)
{
Console.WriteLine("Not a valid input, try again");
continue;
}
// Add minutes exercised to a running total
totalWorkingTime = totalWorkingTime + minutes;
// Display the running total in minutes
Console.Write("Your total working minutes is " + totalWorkingTime + " minutes");
}
}
}
}
}
If the input is "Quit"
The idea is lowering the input to quit, so it will be matched with our condition (entry == "quit")
. We could use another function called toLower as shown below.
if (entry.toLower == "quit")
If the input is 10.3 or 20.32131 or 1.02912
Remember the types of data? It called double type. Integer could not perform addition in comma-formated number, we use double. Just change the integer to double.
For practice, try different input below:
- int z = 5 / 2.5
- int z = (int) (5/2.5)
- int x = (int) 2.8
- 7 / 3
- double y = 7 / 3
- double y = 7 / (double) 3
- double y = 7 / 3.0