Objective
Write a C# function named "GetInt", which displays on screen the text received as a parameter, asks the user for an integer number, repeats if the number is not between the minimum value and the maximum value which are indicated as parameters, and finally returns the entered number:
age = GetInt("Enter your age", 0, 150);
would become:
Enter your age: 180
Not a valid answer. Must be no more than 150.
Enter your age: -2
Not a valid answer. Must be no less than 0.
Enter your age: 20
(the value for the variable "age" would be 20)
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Main method where the program starts
public static void Main()
{
// Call the GetInt function and store the returned value in the age variable
int age = GetInt("Enter your age", 0, 150); // Get the user's age within a valid range
Console.WriteLine("Your age is: " + age); // Output the valid age entered by the user
}
// Function GetInt to request an integer from the user within a specified range
public static int GetInt(string prompt, int min, int max)
{
int result; // Variable to store the user's input
while (true) // Loop indefinitely until a valid input is given
{
Console.Write(prompt + ": "); // Display the prompt to the user
string input = Console.ReadLine(); // Read the user's input
// Check if the input can be converted to an integer
if (int.TryParse(input, out result))
{
// Check if the result is within the specified range
if (result < min)
{
Console.WriteLine($"Not a valid answer. Must be no less than {min}."); // Invalid if less than min
}
else if (result > max)
{
Console.WriteLine($"Not a valid answer. Must be no more than {max}."); // Invalid if greater than max
}
else
{
return result; // Return the valid result
}
}
else
{
Console.WriteLine("Not a valid integer. Please enter a valid number."); // Invalid if not an integer
}
}
}
}