Need assistance with my first calculator

so i just started learning coding, been going at it for about 1 week. i wanted to try and make a calculator that does + and - but cant figure out how to let the user choose what he wants to use, is there anyone that can help me with that? here is the code.

        int x;
        int y;
        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");
        Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

        Console.WriteLine("pls write in you x");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("pls write in your y");
        y = Convert.ToInt32(Console.ReadLine());

        if (x > y)
        {
            Console.WriteLine("you chose to use minus");
            int sum = x - y;
            Console.WriteLine("result: {0}", sum);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("you chose to use plus");
            int sum1 = x + y;
            Console.WriteLine("result: {0}", sum1);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }


     }
}

} as you can see is just used + if the x i lower than y and - if the x is greater than y. the only way i knew how to make it work.

Upvotes: 0

Views: 126

Answers (5)

jeroenh
jeroenh

Reputation: 26782

The naive approach (ask the user) has been answered. But what you probably actually want to achieve is write a full-fledged calculator where the user enters a string like 2+3 and the program simply gives the answer. You're aspiring to write an interpretor.

If you think about it, you will have to perform three tasks:

  • Scanning the user input, and translating it to a series of tokens. This is translating the string "2+3" to the token series 'integer with value 2', 'plus operator', 'integer with value 3'
  • Interpreting the tokens to calculate the result

The more constraints you place on the input (e.g. as you said, only allow + and - to start with), the simpler the code will be (just fail if the input can not be interpreted according to the rules you set out).

If you want to dig deeper, there's numerous resources available on this subject. I enjoyed reading this series of blog posts (the author uses Python, but the principles remain the same).

In the end you will discover that much of what you are trying to do has already been achieved. There are libraries available that already parse and evaluate mathematical expressions (examples: NCalc, Mathos).

On a final note, Roslyn allows you to parse any C# expression easily, so it can also be used to build a simple calculator, like this:

class Program
{
    static void Main(string[] args)
    {
        CSharpReplAsync().Wait();

    }

    private static async Task CSharpReplAsync()
    {
        Console.WriteLine("C# Math REPL");
        Console.WriteLine("You can use any method from System.Math");

        var options = ScriptOptions.Default
            .AddImports("System", "System.Console", "System.Math");

        var state = await CSharpScript.RunAsync("WriteLine(\"Hello from Roslyn\")", options);

        while (true)
        {
            Console.Write("> ");
            string expression = Console.ReadLine();
            if (string.IsNullOrEmpty(expression))
                break;
            try
            {
                state = await state.ContinueWithAsync(expression, options);
                if (state.ReturnValue != null)
                    Console.WriteLine(state.ReturnValue);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Upvotes: 1

user3598756
user3598756

Reputation: 29421

you could go like this

    static void Main(string[] args)
    {
        int x;
        int y;
        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");
        Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

        Console.WriteLine("pls write in you x");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("pls write in your y");
        y = Convert.ToInt32(Console.ReadLine());

        string opt;
        int res;
        do
        {
            Console.Write("Enter your operator [+/-/:/x]:\t");
            opt= Console.ReadLine();
            res = "/+/-/:/x/".IndexOf("/" + opt + "/");

        } while (res == -1);

        double result;
        switch (opt)
        {
            case "+":
                 result= x + y;
                break;
            case "-":
                result = x - y;
                break;
            case ":":
                result = (double)x/(double)y;
                break;
            case "x":
                result = x*y;
                break;

            default:
                result = -9999;
                break;
        }
        Console.WriteLine("\n{0} {1} {2} = {3}", x, opt, y, result);
        Console.ReadLine();

    }

}

Upvotes: 0

lol
lol

Reputation: 635

There are various possible ways to accomplish what you have asked. Simplest of which is asking user to enter operator for corresponding operation:

Here is code for same :

using System.IO;
using System;

class Program
{
    static void Main()
    {
        int x;
        int y;


        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");

        // Reads x and y from console.
        Console.WriteLine("Enter x :");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter y :");
        y = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter operator for corresponding operation on x and y.\nSupported operations x - y and x + y");
        string inputOpr = Console.ReadLine(); // Stores operation to perform

        // Compares input operator to perform operation.
        if (inputOpr == "-"){
            Console.WriteLine("you chose to use minus");
            int result = x - y;
            Console.WriteLine("Result: {0}", result);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }

        else if (inputOpr == "+"){
            Console.WriteLine("you chose to use plus");
            int result = x + y;
            Console.WriteLine("Result: {0}", result);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }
        else{
            Console.WriteLine("Invalid Input");
        }
     }
}

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29036

First of all let me appreciate your try, Now i would add few notes to improve the snippet. You can use int.TryParse for conversion which will help you to handle FormatExceptions, then get the operator from the user and identify it using switch cases and perform the operations according to the user input.

Consider this code as reference, don't copy and paste

int firstNumber, secondNumber;
Console.WriteLine("pls write in you x");
if (!int.TryParse(Console.ReadLine(), out firstNumber))
{
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned");
}
Console.WriteLine("pls write in your y");
if (!int.TryParse(Console.ReadLine(), out secondNumber))
{
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned");
}

/ Now you have two numbers to perform the operation
// You can now prompt the user to enter the operator
Console.WriteLine("pls enter the operator");
char operatorSign = Console.ReadKey().KeyChar;
switch (operatorSign)
{
    case '+' :
        Console.WriteLine("Result {0} + {1} = {2}", firstNumber, secondNumber, firstNumber + secondNumber);
        break;
    case '_':
        Console.WriteLine("Result {0} - {1} = {2}", firstNumber, secondNumber, firstNumber - secondNumber);
        break;
    case '*':
        Console.WriteLine("Result {0} * {1} = {2}", firstNumber, secondNumber, firstNumber * secondNumber);
        break;
    default:             
        Console.WriteLine("Sorry we are not providing this operation");
        break;
}
Console.ReadKey();

Upvotes: 0

Emad
Emad

Reputation: 3939

Welcome to the great world of computer programs. Application development is all about giving options to user and dynamically processing his/her requests. Therefore just as you get values for x and y you might get an operator from user. A simple example would be like this:

int x;
int y;
Console.WriteLine("Welcome to my calculator program!");
Console.WriteLine("This calculator for now can only do + and -");
Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

Console.WriteLine("pls write in you x");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("pls write in your y");
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert operator");
string o = Console.ReadLine();

if (o=="-")
{
    Console.WriteLine("you chose to use minus");
    int sum = x - y;
    Console.WriteLine("result: {0}", sum);
    Console.WriteLine("Press a key to exit");
    Console.ReadLine();
}
else if (o=="+")
{
    Console.WriteLine("you chose to use plus");
    int sum1 = x + y;
    Console.WriteLine("result: {0}", sum1);
    Console.WriteLine("Press a key to exit");
    Console.ReadLine();
}
else
{
    Console.WriteLine("the operator is not recognized");
}

Please mark the answer if you found it useful.

Upvotes: 0

Related Questions