-3

I'm making a simple guessing game in C# where the computer generate a number between 1-10, and I got both a clickEvent and a KeyPressedEvent (to the Enter key) to "submit" the guess.

I'm trying to make it so you can just type "reset" into the text field and hit enter to call on the StartNewGame() method but it doesn't seem to activate the method.

GIF of what I'm talking about

I tried both

if (userReset.Equals("reset"))
    {
        StartNewGame();
    }

and

if (userReset == "reset" )
    {
        StartNewGame();
    }

but it does not seem to call on that StartNewGame()

Image of the code

I'm using Visual Studio 2019 on Windows 10.

jp1955
  • 35
  • 4

1 Answers1

3

The problem with the code is that the variable userReset is set to an empty string, and nothing else:

String userReset = "";

Therefore, when you are comparing it to the text "reset" the result is false.

Instead you should perhaps implement it like this:

...
string userReset = txtGuess.Text
...

if (userReset.Equals("reset"))
...

Or alternatively, don't use a variable at all:

...
if (txtGuess.Text == "reset")
...

Incidentally, I would personally use this in the else from the int.TryParse:

if (int.TryParse(txtGuess.Text, out guess))
{
    ...
}
else if (txtGuess.Text == "reset")
{
    ...
}

This is because if the text is a number then it will never be "reset" (and vice versa) which saves checking the value of the TextBox unnecessarily.

Further edit regarding case

As pointed out by @TimSchmelter in the comments, it may also make sense to ignore the case of the text being entered (i.e. make the comparison case-insensitive) so that the user could type reset, Reset, ReSeT, etc.

To achieve this, use a case-insensitive comparison:

else if (txtGuess.Text.Equals("reset", StringComparison.OrdinalIgnoreCase))
Martin
  • 16,093
  • 1
  • 29
  • 48
  • 2
    It might be better to ignore the case: `else if (txtGuess.Text.Equals("reset", StringComparison.OrdinalIgnoreCase))` – Tim Schmelter Jul 29 '21 at 09:27
  • 1
    @TimSchmelter Good idea - I've updated the question to include this. I didn't include that as OP had specifically used lowercase `reset` in their code but it's good for completeness. Thank you – Martin Jul 29 '21 at 09:31
  • Thanks for this, worked perfectly. In my head I kept thinking that I needed an empty string to store the result. – jp1955 Aug 02 '21 at 04:20
  • 1
    @jp1955 You're welcome. Please ensure that you mark this answer as correct if it solved your problem, and also upvote any helpful answers – Martin Aug 02 '21 at 08:12