I am having trouble validating user input, I have the following loop which definitely catches it but when the loop starts again the user doesn't have a chance to enter a different value so the value is the same and just creates an endless loop.
private void guess_Click(object sender, EventArgs e)
{
int guessInt = 0;
bool pass = false;
int number;
while (pass == false)
{
if (guessInput.Text != "")
{
pass = Int32.TryParse(guessInput.Text, out number);
if (pass)
{
guessInt = number;
}
else
{
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
guessInput.Text = "";
}
}
else MessageBox.Show("You did not enter anything, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
guess.Enabled = false;
next_Guess.Enabled = true;
if (guessInt == randomArray[x])
{
result.Text = ("You Win! The correct number was " + randomArray[x]);
right += 1;
correctAnswers.Text = right.ToString();
}
else
{
result.Text = ("Sorry you lose, the number is " + randomArray[x]);
wrong += 1;
incorrectAnswers.Text = wrong.ToString();
}
hintLabel.Enabled = false;
x++;
}
So how can the user have a chance to reenter a value and the loop start again or should I be using a try/catch attempt here?
break;and then start the loop again when user enters a different value.breakthe loop andreturnthevoidor you can maintain aboolwhich will hold the success/fail of the loop.