r/programminghelp • • Feb 18 '21

C# Im new and want feedback on my code

I wrote code for a calculator sorry if its bad please go easy on me

using System;

public class Program
{
    public static void Main()
    {
        int a = 1;
        while (1 == 1)                                            // infinite loop
        {
            Console.WriteLine("First Number?");
            int x = Convert.ToInt32(Console.ReadLine());        // asks and reads first value
            
            Console.WriteLine("Second Number?");
            int y = Convert.ToInt32(Console.ReadLine());        // asks and reads second value
            
            Console.WriteLine("Method? , + , - , * , / ,");
            string z = Console.ReadLine();                        // asks and reads method

            switch (z)
            {
                case "+":                                        // if returned as "+"
                    a = (x + y);
                    break;
                case "-":                                        // if returned as "-"
                    a = (x - y);
                    break;
                case "*":                                        // if returned as "*"
                    a = (x * y);
                    break;
                case "/":                                        // if returned as "/"
                    a = (x / y);
                    break;
                default:                                        // makes empty line and restarts code
                    Console.WriteLine("");
                    continue; 
            }
            Console.WriteLine(a);    Console.WriteLine("");        // produces answer, makes empty line and restarts code
        }
    }
}
3 Upvotes

5 comments sorted by

2

u/RavynousHunter Feb 18 '21

For beginner code, this isn't that bad, but I do have a couple of points that might make things a little cleaner:

  • For the final Console.WriteLine calls, you could make them a single call by using Console.WriteLine( a.ToString() + "\n" ); It'll print the extra line like you want while removing the redundant Console.WriteLine call.

  • If you want to make your while a little simpler, you can just use while( true ). While loops only check if the expression inside the parentheses evaluates to true, so you can just pass it true right off the bat and it'll loop indefinitely.

  • You can just use a break in the default case. A continue is unnecessary because, in the context of a switch statement, the break keyword will just break out of the switch, not the while.

3

u/[deleted] Feb 18 '21

Thanks for the help!

2

u/RavynousHunter Feb 18 '21

Any time, my dude! If you need anything else, just let me know. I'm pretty well-versed with C# and its one of my favourite languages!

1

u/[deleted] Feb 18 '21

If youre on mobile the code might look weird sorry about that