0

I'm making a guessing game where the program generates a random number from 0 to 10 and the user tries to guess it. I want the user to input an integer in a Text Area. Then I convert the input to integer. Here comes the problem: How do I do something if the input is an unconvertable string? Like "asdf". I want the program to output "I asked for a number!! not word dumbass!" but C# converts even things like "Aadsda" to 0.. what do i do?

This is what I tried:

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            int.TryParse(textBox_Guess.Text, out guess);
            //IF STATEMENTS TO CHECK HOW CLOSE THE USER'S GUESS IS
        }
        catch (Exception)
        {
            //Since all strings are converted, this block is never executed

            label_Reveal.ForeColor = System.Drawing.Color.Red;
            label_Reveal.Text = "Your input is invalid!";
            label_Reveal.Show();

        }
    }
Jannik
  • 2,310
  • 6
  • 32
  • 61
Zero Cipher
  • 78
  • 1
  • 12
  • 2
    I believe TryParse returns a boolean value which tells you if it was successful. – Chris Oct 03 '15 at 12:13
  • BTW: A littlebit offtopic, but the reason why TryParse returns a zero even if the method failed to convert it, is, because the default value of an integer is 0 – Jannik Oct 03 '15 at 12:22
  • okay that made sense.LESSON: TryParse is a BOOLEAN – Zero Cipher Oct 03 '15 at 12:23
  • @Chris don't wanna spam but there's a hell of a similarity between your account and my account, my name and rep are the same!! :D – Christo S. Christov Oct 03 '15 at 12:23
  • Please don't ever do `catch (Exception)` - it's even worse than using `goto` and just hides buggy code. – Enigmativity Oct 03 '15 at 13:30
  • i deleted my answer because i found other answers more helpful. but it worth a look at here. http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers – M.kazem Akhgary Oct 03 '15 at 13:51

6 Answers6

2
if(int.TryParse(textBox_Guess.Text, out guess)){
    //successfully parsed, continue work
}
else {
    //here you can write your error message.
}
Christo S. Christov
  • 2,268
  • 3
  • 32
  • 57
2

TryParse returns a boolean. With the boolean you can decide, whether it was sucessfully parsed or not.

if(int.TryParse(..)
{
      //If parsed sucessfully
}
else
{
      //Wasn't able to parse it
}
Jannik
  • 2,310
  • 6
  • 32
  • 61
2

The TryXYZ pattern, with functions like TryParse, attempts to avoid having to rely on exceptions when parsing strings into other types. A more appropriate usage of the function to accomplish what you are attempting could be implemented like so:

var guessString = textBox_Guess.Text;
int guessParsed;
var success = int.TryParse(guessString, out guessParsed);
if(!success) {
    label_Reveal.ForeColor = System.Drawing.Color.Red;
    label_Reveal.Text = "Your input is invalid!";
    label_Reveal.Show();
}
Jonathon Chase
  • 9,396
  • 21
  • 39
1

You can change your code as follows:

private void button1_Click(object sender, EventArgs e)
{
    int num;
    bool guessCorrect = int.TryParse(textBox_Guess.Text, out num);
    if(!guessCorrect){
        label_Reveal.ForeColor = System.Drawing.Color.Red;
        label_Reveal.Text = "Your input is invalid!";
        label_Reveal.Show();
    }
}
wingerse
  • 3,670
  • 1
  • 29
  • 61
0

Use int.Parse() instead for int.TryParse() then you will get exception:

The int.Parse method is strict. With an invalid string, it throws a FormatException. We can catch this using a try-catch construct.

But: Using the int.TryParse method is usually a better solution. TryParse is faster,It's a method for parsing integers is the int.TryParse method. The parsing logic in TryParse is the same. But the way we call it is different.

If you are okey with int.Parse() then you can use the following,

try
{
   guess=int.Parse(textBox_Guess.Text);          
}
catch
{
    label_Reveal.ForeColor = System.Drawing.Color.Red;
    label_Reveal.Text = "Your input is invalid!";    
    label_Reveal.Visible = true;      
}

Or else you should use TryParse with if as described below:

if(!int.TryParse(textBox_Guess.Text, out guess))
{
   label_Reveal.ForeColor = System.Drawing.Color.Red;
   label_Reveal.Text = "Your input is invalid!";    
   label_Reveal.Visible = true;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • What's the point in throwing and then catching an exception when you can handle the situation without the extra boilerplate with TryParse? – Christo S. Christov Oct 03 '15 at 12:20
  • Using exceptions for program flow is a very bad idea. That's why the `TryParse` methods were added to the framework to avoid this. – Enigmativity Oct 03 '15 at 13:33
0

You don't need int.TryParse, use int.Parse, if you want to handle exception:

void button1_Click(object sender, EventArgs e)
{
    try
    {
        guess = int.Parse(textBox_Guess.Text);

    }
    catch (Exception)
    {
        label_Reveal.ForeColor = System.Drawing.Color.Red;
        label_Reveal.Text = "Your input is invalid!";
        label_Reveal.Show();
    }
}

Or, if you prefer TryParse then handle it within if statement like this:

if(!int.TryParse(textBox_Guess.Text, out guess))
{
    // manage parsing error here
}
drty
  • 200
  • 1
  • 11
  • 1
    Using exceptions for program flow is a very bad idea. That's why the `TryParse` methods were added to the framework to avoid this. – Enigmativity Oct 03 '15 at 13:32
  • In ideal world - maybe. But not when .NET code itself violates this rule in too many scenarios. – drty Oct 03 '15 at 14:15
  • That's true, but that doesn't stop it being a bad idea and it shouldn't be an excuse to do the wrong thing when you don't have to. – Enigmativity Oct 04 '15 at 02:28