Click here to Skip to main content
15,887,867 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I wrote this program and asks a user to guess a number between 20 and 30 and to avoid the user entering something like a letter, I used a certain code but I would like to know how to use the tryParse method. Could someone please put the tryParse method in my code?

C#
using System;

class ApplicationEntry
 Collapse | Copy Code
{
static void Main(string[] args)
{
bool repeat = true, repeat2 = true, repeat3 = true;
while (repeat == true)
{
repeat2 = true;
Random r = new Random();
int numb = (r.Next(20, 30));
 Collapse | Copy Code

while (repeat2 == true)
{
Console.WriteLine("Please enter a numbers between 20 and 30");
int guess1 = Convert.ToInt32(Console.ReadLine());

if ((guess1 < 20 || guess1 > 30) && guess1 != numb)
{
Console.WriteLine("Invalid. Please enter a number between 20 and 30");
repeat3 = false;
}
else if (guess1 == numb)
{
Console.WriteLine("Good job");
repeat2 = false;
repeat3 = true;
}
else
{
Console.WriteLine("Wrong! Try again");
repeat2 = true;
repeat3 = false;
}
while (repeat3 == true)
{
Console.WriteLine("Would you like to play again?");
string answer = Console.ReadLine();
if (answer == "yes" || answer == "Yes" || answer == "YES")
{
repeat3 = false;
repeat = true;
repeat2 = false;
}
else if (answer == "no" || answer == "No" || answer == "NO")
{
repeat = false;
repeat3 = false;
}
else
{
Console.WriteLine("I didn't understand that");
}


}

}
}

Console.Write("\nPress any key to exit program: ");
Console.ReadKey();
}

}
Posted

Instead of writing this statement
int guess1 = Convert.ToInt32(Console.ReadLine());


Try TryParse method to check invalid entries like characters, read more [^]

int guess1;
bool result = Int32.TryParse(Console.ReadLine(), out guess1);
if (result)
{
   //successfully converted into Int value        
}
else
{
   //invalid entry, try again
   //continue;
}
 
Share this answer
 
C#
if (!int.TryParse(Console.ReadLine(), guess1)
{
     Console.WriteLine("Invalid. Please enter a number between 20 and 30");
}


So the tryParse takes the string (Console.ReadLine()) and tries to parse it to an integer, putting the result (if it succeeds) in guess1.

The function returns a boolean - false if the conversion fails -
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900