Question Having to enter word twice

JayvanGeld

New member
Joined
Mar 16, 2020
Messages
2
Programming Experience
Beginner
I'm kinda new with C# in Visual Studio, and don't know why I'm having this issue. I'm trying to code a simple calculator and when I enter divide, add or subtract I have to enter it twice for the code to recognise it. Entering multiply works fine.

Code:

Console.WriteLine("Do you want to multiply, divide, add or subtract?");

if (Console.ReadLine() == "multiply")
{
Console.WriteLine("multiplying");
}
else if (Console.ReadLine() == "divide")
{
Console.WriteLine("dividing");
}
else if (Console.ReadLine() == "add")
{
Console.WriteLine("adding");
}
else if (Console.ReadLine() == "subtract")
{
Console.WriteLine("subtracting");
}
 
insertcode.png


Console.ReadLine isn't a variable that holds the last input, it is a method that reads a line input and returns it once. Each time you call it the user must input a line.
To solve it welcome C# Variables
 
Console.WriteLine("Do you want to multiply, divide, add or subtract?");
You need to call for user input. Where are you doing that?

The reason you need to press enter twice is because you are not calling to read the users input. Console.ReadLine Method (System)

What you could also do is not call ReadLine all the time and use variables to check your logic against.

C#:
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Do you want to multiply, divide, add or subtract?");
            Response.Console_Response = Console.ReadLine();
            if (Response.Console_Response == "multiply")
            {
                Console.WriteLine("multiplying");
            }
            Console.WriteLine("You're done. Press 'E' key to exit.");
            if (Console.ReadKey().Key == ConsoleKey.E)
                Console.WriteLine();
            else
            {
                Console.WriteLine("What do you want to do if not exit?"); Console.ReadLine();
            }
        }
        private static class Response
        {
            private static string response;
            public static string Console_Response { get { return response; } set { response = value; } 
        }
    }

That's just to test with. There is a debugger tutorial in my signature you should read, and follow and use it to move through the above code.

Console.ReadLine waits for user input. If you don't check for user input, how to you expect to get any if you don't read it?

The next problem you will have with your current code is that when your statements are met, your console will exit. This can also be prevented by calling ReadLine.
 
Thanks, I got it working by setting a variable to the Console.ReadLine, and checked if it was one of the options.

Also is there a way to set this thread to solved?
 
Back
Top Bottom