Let’s extract a method (ReadInteger
) for it. Please, note, that we use int.TryParse
instead of Convert.ToInt32
since user input is not necessary a valid integer
private static int ReadInteger(String title = null)
{
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true)
{
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, the input is not a valid integer, try again");
}
}
Then we can use it:
public void Play()
{
while (true)
{
// We should re-read value after each attempt
int value = ReadInteger();
if (value > theNumber)
{
Console.WriteLine("your number is too big");
}
else if (value < theNumber)
{
Console.WriteLine("your number is too big");
}
else
{
Console.WriteLine("you got it");
break;
}
}
}
2
solved scanner in while loop [duplicate]