Difference between revisions of "The number of years should be between 0 and 5 but no validation takes place"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "<syntaxhighlight lang=csharp line> static int GetHowLongToRun() { int Years = 0; Console.WriteLine("Welcome to the Plant Growing Simulation"); Console.Wr...")
 
Line 23: Line 23:
 
     }
 
     }
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
==Explanation==
 +
 +
Line 11: While loop added so that if the user inputs an invalid number, there is a way for them to input again, an unlimited number of times.
 +
 +
Line 15: Checks if the value of years is between -1 and 5 (all valid inputs).
 +
 +
Line 16: If line 15 is true, the program will break out of the while loop and continue as usual.
 +
 +
Line 17/18: If the above if statement is false, the user will be prompted to add a valid number.

Revision as of 15:03, 9 March 2017

 1 static int GetHowLongToRun()
 2     {
 3       int Years = 0;
 4       Console.WriteLine("Welcome to the Plant Growing Simulation");
 5       Console.WriteLine();
 6       Console.WriteLine("You can step through the simulation a year at a time");
 7       Console.WriteLine("or run the simulation for 0 to 5 years");
 8       Console.WriteLine("How many years do you want the simulation to run?");
 9       Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ");
10 
11       while(true)
12       {
13           Years = Convert.ToInt32(Console.ReadLine());
14 
15           if (Years >= -1 && Years <= 5)
16               break;           
17           else
18               Console.Write("You MUST Enter a number between 0 and 5, or -1 for stepping mode: ");
19       }
20 
21       return Years;
22     }

Explanation

Line 11: While loop added so that if the user inputs an invalid number, there is a way for them to input again, an unlimited number of times.

Line 15: Checks if the value of years is between -1 and 5 (all valid inputs).

Line 16: If line 15 is true, the program will break out of the while loop and continue as usual.

Line 17/18: If the above if statement is false, the user will be prompted to add a valid number.