Write a user defined method named getMark that can be used to get a valid mark from the user. Your method must continuously ask the user for a mark, until a valid mark is entered (valid marks are between 0 and 100). If a user enters an invalid mark, display an error message before asking for a valid mark to be entered. The method must return the valid value to the calling program.
Solution example:
using System;
/*
* Write a user defined method named getMark that can be used to get a valid mark from
* the user. Your method must continuously ask the user for a mark, until a valid mark
* is entered (valid marks are between 0 and 100). If a user enters an invalid mark,
* display an error message before asking for a valid mark to be entered. The method
* must return the valid value to the calling program.
*/
namespace getMark
{
class Program
{
static void Main(string[] args)
{
int mark = getMark();
}
public static int getMark()
{
int mark;
do
{
Console.WriteLine("Input a mark value between 0 and 100.");
string input = Console.ReadLine();
try
{
mark = int.Parse(input);
if (mark >= 0 && mark <= 100)
{
return mark;
}
else
{
Console.WriteLine("Input an invalid mark value!");
}
}
catch (Exception)
{
Console.WriteLine("Input an invalid mark value!");
}
}
while (true);
}
}
}
Comments
Leave a comment