0

I made this Basic C# Calculator to reflect on what I've learned these past few days. I'm an absolute beginner and I wanted to get suggestions on improving and shortening it.

I've tried to add switch statements and multiple methods, but it has been really hard grasping them.

using System;

namespace lol
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine("Hi! What is your name?");
        string name = Console.ReadLine();

        Console.WriteLine(name + " What do you wanna do?");

        Console.WriteLine("Type \"+\" for addition");
        Console.WriteLine("Type \"-\" for Subraction");
        Console.WriteLine("Type \"*\" for Multiplication");
        Console.WriteLine("Type \"/\" for division");

        string operation = Console.ReadLine();

        Console.Write("Now, Give me number one: ");
        double num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Now give me number two: ");
        double num2 = Convert.ToDouble(Console.ReadLine());

        if (operation == "+")
        {
            Console.WriteLine(num1 + num2);
        }
        else if (operation == "-")
        {
            Console.WriteLine(num1 - num2);
        }

        else if (operation == "*")
        {
            Console.WriteLine(num1 * num2);
        }

        else
        {
            Console.WriteLine(num1 / num2);

        }

    }
  }
}
17
  • 6
    I don't think a calculator needs to know your name. Commented Aug 9, 2019 at 6:14
  • 2
    you can use switch instead of if , else other thing looks ok Commented Aug 9, 2019 at 6:14
  • 1
    Could you show those "switch statements" and "methods" that you tried and tell about the issues you are having with them? Commented Aug 9, 2019 at 6:14
  • @FalcoGer yeah, but I was just trying to add as must stuff as possible inside this. To be honest I think got a little too excited writing a proper first program. Commented Aug 9, 2019 at 6:16
  • instead of string compare, you could use enums for the operation Commented Aug 9, 2019 at 6:17

2 Answers 2

1

If it better for your eyes, you can write like that:

static class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hi! What is your name?");
        string name = Console.ReadLine();

        Console.WriteLine(name + " What do you wanna do?");
        string[] operations = new string[] { "\"+\" for addition", "\"-\" for subtraction", "\"*\" for multiplication", "\"/\" for divsion" };
        foreach (string operation in operations) { Console.WriteLine("Type " + operation); }

        string cmd = Console.ReadLine();

        Console.Write("Now, Give me number one: ");
        double num1 = Convert.ToDouble(Console.ReadLine());

        Console.Write("Now give me number two: ");
        double num2 = Convert.ToDouble(Console.ReadLine());

        switch (cmd)
        {
            case "+": Console.WriteLine(num1 + num2); break;
            case "-": Console.WriteLine(num1 - num2); break;
            case "*": Console.WriteLine(num1 * num2); break;
            case "/": Console.WriteLine(num1 / num2); break;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This certainly does help! I'm still a beginner, so I'd have to Understand some things you did in there. But thanks!
1

Using enums and checking if the user input is valid. I also added a loop that checks if the user wants to input equations. References:

You can try it here: https://dotnetfiddle.net/aIwX5P

using System;

public class Program
{
    enum eOperator
    {
        opAdd = 0,
        opSub = 1,
        opDiv = 2,
        opMul = 3,
        opInvalid = int.MinValue + 1,
        opQuit = int.MinValue
    }
    public static void Main()
    {
        double a = 0.0, b = 0.0;
        eOperator op = eOperator.opQuit;
        string input = String.Empty;
        Console.WriteLine("Calculator");
        Console.WriteLine("Enter 'quit' at any time to exit.");
        // repeat until the user wants to quit.
        do // while(op != eOperator.opQuit)
        {
            Console.Write("a = ");
            input = Console.ReadLine().ToLower().Trim();
            if (double.TryParse(input, out a))
            {
                // input is a valid double and was stored in a
                Console.Write("Operator: ");
                input = Console.ReadLine().ToLower().Trim();
                switch (input)
                {
                    case "+":
                        op = eOperator.opAdd;
                        break;
                    case "-":
                        op = eOperator.opSub;
                        break;
                    case "*":
                        op = eOperator.opMul;
                        break;
                    case "/":
                        op = eOperator.opDiv;
                        break;
                    case "quit":
                        op = eOperator.opQuit;
                        break;
                    default:
                        op = eOperator.opInvalid; // can't be left as quit
                        Console.WriteLine("Invalid entry. +, -, *, / or quit for operator.");
                        break;
                }
                if (op != eOperator.opQuit && op != eOperator.opInvalid)
                {
                    // user didn't choose to quit or type something invalid
                    Console.Write("b = ");
                    input = Console.ReadLine().ToLower().Trim();
                    if (double.TryParse(input, out b))
                    {
                        // input is a valid double and was parsed into b
                        double result = a; // we use the operator on a, so we might as well just store a into the result right away.
                        // do the operation on result.
                        switch (op)
                        {
                            case eOperator.opAdd:
                                result += b;
                                break;
                            case eOperator.opSub:
                                result -= b;
                                break;
                            case eOperator.opMul:
                                result *= b;
                                break;
                            case eOperator.opDiv:
                                // Div by 0 check. without this, this still works since double has +/- inf values.
                                if (b != 0.0) // comparing double with = and != is usually bad idea, but 0.0 is saved without rounding errors.
                                {
                                    result /= b;
                                }
                                else
                                {
                                    Console.WriteLine("Div by 0");
                                    op = eOperator.opInvalid;
                                }
                                break;
                            default:
                                // this if branch checked for the other two operators. since we never chanced op after that check, this exception should never happen.
                                // it is still a good idea to include it to find errors in your logic, should they have occurred.
                                throw new Exception("This shouldn't happen.");
                        }
                        if (op != eOperator.opInvalid)
                        {
                            Console.WriteLine("Result: " + result.ToString());
                        }
                        // the only invalid operation is div by 0 for now. the message was sent to the user in that case, so no else is needed at this point.
                        // alternatively you can store an error message into a string, and when op = opInvalid, then display that error message here centralized.
                        // this would be a good idea if multiple things can go wrong.
                    }
                    else if (input == "quit")
                    {
                        // input for b was an invalid number, but input was 'quit'
                        op = eOperator.opQuit;
                    }
                    else
                    {
                        // input for b was an invalid number and also not 'quit', display error message
                        Console.WriteLine("Invalid entry. Type a number or Quit");
                    }
                }
            }
            else if (input == "quit")
            {
                // input for a was invalid number, but 'quit'
                op = eOperator.opQuit;
            }
            else
            {
                // input for a was invalid number and also not 'quit'
                Console.WriteLine("Invalid entry. Type a number or Quit");
            }
        // repeat until the user wants to quit.
        }while(op != eOperator.opQuit);
        Console.WriteLine("Bye");
    }
}

4 Comments

Thank you for that! I'll Look into it and search for those topics.
I'll say this though. It looks Really advanced.
if you want advanced you could try equation parsing :P
@AhmadDaPenguinz i included some links to msdn for enums, select case statements and input checking with tryparse.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.