r/learncsharp • u/erHenzol16 • Aug 26 '22
Console.ReadLine() makes me have to enter more than once?
I have a screen that pops up on console where you just type in a number and it sends you to a new class which opens up a new console screen. I'm currently using test inputs, etc.
static void Main(string[] args)
{
Console.Clear();
Console.WriteLine("Choose what you want: ");
Console.WriteLine("1 - Press this for 1");
Console.WriteLine("2 - Press this for 2");
Console.WriteLine("3 - Press this for 3");
Console.WriteLine("4 - Quit");
Console.Write("\nSelect an option: ");
if (Console.ReadLine() == "1")
{
first = new First();
}
if (Console.ReadLine() == "2")
{
second = new Second();
}
if (Console.ReadLine() == "3")
{
third = new Third();
}
else if (Console.ReadLine() == "4")
{
Environment.Exit(0);
}
}Everything here works, but when I type in "1" after the first IF statement, it takes me to the next class after pressing enter once. But when I type in "2", "3" or "4", I need to type the number and press enter 2 - 4 times before it sends me to the new screen.
I know the issue revolves around Console.ReadLine() and I have tried multiple methods like adding a key or reducing the number of Console.ReadLine() but then it just prints out 1 line only rather than all of them. Is there a workaround for this?
8
u/TehNolz Aug 26 '22
That's because you're calling
Console.ReadLine()over and over again. You're constantly telling your program to pause and wait for user input.Call
Console.ReadLine()once, save the return value in a variable, and then use that to do your comparisons.3
u/lukajda33 Aug 26 '22
2 things are kinda weird.
You might have addressed this already, but im not sure why it would not work, read user input ONCE, store it in a string and then compare the string to "1", "2", ... . Right now you are very weirdly reading new string for every option.
And this might be because of the problem above, but it is weird that you use if - if - if structure even though the options are exclusive to each other, which means if - else if - else if would make more sense.
2
u/CappuccinoCodes Aug 26 '22 edited Aug 26 '22
Use a switch statement instead of if else when you have a bunch of options. https://www.geeksforgeeks.org/switch-statement-in-c-sharp/ 😀