Request Help about a simple c# program!

Exceeta

New Member
So basically I have this piece of code and I want to add a validation that returns the user a warning if he enters a string instead of an integer. Any help would be appreciated :)

Console.WriteLine("Rating " + (i + 1) + " : ");
int ratings;
do
{
ratings = Convert.ToInt32(Console.ReadLine());
if (ratings < 1 || ratings > 5)
{
Console.WriteLine("Rating entered is not within range. Please enter a number between 1 and 5");
}


} while (ratings < 1 || ratings > 5 );
ratingsList = ratings;
}
break;
 
well in java, you could use a try catch statement for something like this.(I'll try to stick to c#, at least, what i can gather from it using your code snippet)

try
{
ratings=Convert.ToInt32(Console.ReadLine());
}
catch (NumberFormatException exception)
{
Console.WriteLine("Entered String, Please enter a number between 1 and 5");
}


so, I'm assuming c# has some function like that.
 
You want to read the user input as a string (from the console, a textbox or whatever input method you are using) then use int.TryParse.

ie.

String fromUser = console.ReadLine();

int number;

if (int.TryParse(userInput, out number)){
//its a number, and now the contents are in the "number" variable
}
else {
//its not a number
}




Or using the exception idea above:
Console.WriteLine("Rating " + (i + 1) + " : ");
int ratings;
do
{
try {
ratings = Convert.ToInt32(Console.ReadLine());
if (ratings < 1 || ratings > 5)
{
Console.WriteLine("Rating entered is not within range. Please enter a number between 1 and 5");
}
}
Catch (Exception ex)
{
//wasnt a number
}
} while (ratings < 1 || ratings > 5 );
ratingsList = ratings;
}
break;
 
Last edited:
Back
Top