+ 1
[SOLVED] [C#] How can I make a repeating when the number is incorrect?
So, I tried to do like repeating when the user's answer isn't right. Like this: string a = "1"; string b = "2"; string ans = ""; if (ans != a && ans != b) { while(ans != a || ans != b) { Console.Write("\nEnter the ID of the room that you want to join: "); ans = Console.ReadLine(); } } But when I'm trying to enter the correct string, like 1 or 2 it's repeating the message again and doing nothing. Need help, guys :)
3 Answers
+ 2
To add onto what you're doing, if you look at your while loop, the IF statement inside of it isn't necessary. It's the same as your while condition, so as long as the while loop is still iterating, that IF statement is also true.
while (ans != a && ans != b)
{
Console.WriteLine("Invalid option! Try again.");
Console.Write("Enter the ID of the room that you want to join: (1-2) ");
ans = Console.ReadLine();
}
Also, I know this is just practice, but if it was a real application, make sure that you inform your users of what options are available to them and why their input was erroneous. This helps ensure proper input by the user, as well it improves the user experience so they don't get frustrated and stop using your software. HCI is always important.
+ 2
Since you got me invested, here is another take on it:
Disclaimer: SoloLearn won't let you enter inputs again after you run the code, so you'll want to place all of your test inputs, one on each line, when you first run it.
When prompted for input, input this:
3
0
2
https://code.sololearn.com/cL0DmB7Oum9w/#cs
const int MAX_OPTIONS = 2;
int userInput = 0;
while(true){
Console.WriteLine("Please enter the Room ID (1-" + MAX_OPTIONS + "): ");
userInput = Convert.ToInt32(Console.ReadLine());
if(userInput > MAX_OPTIONS || userInput <= 0) {
Console.WriteLine("Invalid option! Try again.");
continue;
} else {
Console.WriteLine("You've successfully joined Room " + userInput + "!");
break;
}
}
Console.WriteLine("Thank you for using! Goodbye.");
+ 1
Problem is solved:
string a = "1";
string b = "2";
string ans = "";
Console.Write("\nEnter the ID of the room that you want to join: ");
ans = Console.ReadLine();
while (ans != a && ans != b)
{
if (ans != a && ans != b)
{
Console.Write("Try again: ");
ans = Console.ReadLine();
}
}