Reputation: 145
I recently started coding with c#, but I have encountered a problem that I have been trying to solve for a few hours now, so I thought I would give this a go. This is basically a simple program where the user can guess on a number between 1-20 and the computer will tell you if the number is too small or too big or if its the correct number.
Everything works fine except the try and catch part. I want the user to get an error message everytime they input a string instead of a number. I have tried different solutions but I can't work out what I have to put into the try block. As i said the program works fine when I don't use the try and catch, but when I use it the error message comes up every single time, so please help me and tell me what I have to write in the try part of the code.
this is the code:
using System;
namespace Uppgift_4
{
class Program
{
static void Main(string[] args)
{
Random slumpat = new Random();
int speltal = slumpat.Next(1,20);
bool spela = true;
while (spela)
{
Console.Write("\n\tGissa på ett tal mellan 1 och 20: ");
int tal;
Int32.TryParse(Console.ReadLine(), out tal);
try
{
}
catch
{
Console.WriteLine("Fel, du får bara skriva in nummer");
}
if (tal < speltal)
{
Console.WriteLine("\tDet inmatade talet " + tal + " är för litet, försök igen.");
}
else if (tal > speltal)
{
Console.WriteLine("\tDet inmatade talet " + tal + " är för stort, försök igen.");
}
else
{
Console.WriteLine("\tGrattis, du gissade rätt!");
spela = false;
}
}
}
}
}
Upvotes: 1
Views: 495
Reputation: 236208
When you use Int32.TryParse
no exception will be thrown if given string cannot be parsed as integer number. This method will just return false
. And you should check it:
Console.Write("\n\tGissa på ett tal mellan 1 och 20: ");
int tal;
if(!Int32.TryParse(Console.ReadLine(), out tal))
{
Console.WriteLine("Fel, du får bara skriva in nummer");
continue;
}
When you use Int32.Parse
then exception will be thrown if string cannot be parsed:
Console.Write("\n\tGissa på ett tal mellan 1 och 20: ");
int tal;
try
{
tal = Int32.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Fel, du får bara skriva in nummer");
continue;
}
Upvotes: 2