Here is a brief example that shows how to validate user input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
///
/// This program uses the quadratic equation
/// to produce a a prime number
/// with a seed of any integer between 1 and 41
/// The main purpose is to show you how you
/// can validate the users input.
/// the TryParse makes sure that the number
/// is an integer without crashing the program
/// the while loop keeps repeating the user prompt
/// until they enter an integer in the valid range
/// Steve Conger 11/1/2012
///
static void Main(string[] args)
{
Program p = new Program();
p.HowToTestUserEntry();
Console.ReadKey();
}
private void HowToTestUserEntry()
{
//you want them to enter an integer between 1 and 41
//declare the variabe to test
int number = 0;
//create a loop that won't stop until
//they enter a proper number
while (number < 1 || number > 41)
{
Console.WriteLine("Enter an integer between 1 and 41");
//if it parses correctly it will assign the integer to the
//variable number, otherwise it returns false
bool entry = int.TryParse(Console.ReadLine(), out number);
//if it is false or the number is not between
//1 and 41 prompt them to enter a correct number
if (!entry || number < 1 || number > 41)
{
Console.WriteLine("Please make sure you entered an integer between 1 and 41");
}//end if
}//end while
//this equation is a mathematical oddity
//that returns 41 prime numbers in sequence
//for numbers between 1 and 41
int prime = number * number - number + 41;
Console.WriteLine("The prime number is {0}", prime);
}
}
}
No comments:
Post a Comment