Home > OS >  End Chain \n C#
End Chain \n C#

Time:12-05

I have this code, and when I run it it runs properly, but I've got a problem, it prints all input, all options, not only the one I choose. I know it's because of \n, but I don't know how to end that chain and get to the following one. Can you give me an advise?

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a number");
            int number = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter a second number");
            int number2 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine($"Choose an operation: \n 1. add\n 2. minus \n 3. divide \n\0 4. multiply");
            Console.ReadLine();
            var add = number   number2;
            Console.WriteLine($"{number   number2}");
            var minus = number - number2;
            Console.WriteLine($"{number - number2}");
            var divide = number / number2;
            Console.WriteLine($"{number / number2}");
            var multiply = number * number2;
            Console.WriteLine($"{number * number2}");

        }
     }

}

CodePudding user response:

You’re off to a good start. You still need to assign the user’s choice to a variable just like you did with number1 and number2. Next you’ll want to use a conditional statement to choose which result to display based on the user’s choice. A series of if/else would work but a switch statement would probably work best.

CodePudding user response:

It actually doesn't have to do with the \n. You're asking for the user to select one of the operations, but the code doesn't check the option against anything. You should store the Console.ReadLine() below the "Choose an Operation" as a variable. Below that, put the individual operations in if blocks. Below is what you might want to do (but you can expand it to more operations).

Console.WriteLine($"Choose an operation: \n 1. add\n 2. minus \n 3. divide \n\0 4. multiply");
int operation = Console.ReadLine();
if (operation == 1) {
   var add = number   number2;
   Console.WriteLine($"{number   number2}");
} else if (operation == 2) {
   var minus = number - number2;
   Console.WriteLine($"{number - number2}");
}

Alternatively, you can use a switch statement, since you're checking the value of one variable:

switch (operation) {
    case 1:
        var add = number   number2;
        Console.WriteLine($"{number   number2}");
        break;
    case 2:
        var minus = number - number2;
        Console.WriteLine($"{number - number2}");
        break;
}
  •  Tags:  
  • c#
  • Related