Last active
September 10, 2020 02:35
-
-
Save ZacharyPatten/008ac384e4880799d9d51bf32094183c to your computer and use it in GitHub Desktop.
Calculator Example For C# Beginners
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| namespace Example | |
| { | |
| class Program | |
| { | |
| static string[] Operators = { "+", "-", "*", "/" }; | |
| static void Main() | |
| { | |
| Console.WriteLine("Calculator"); | |
| Console.WriteLine($"Supported Operations: {string.Join(", ", Operators)}"); | |
| Console.WriteLine(); | |
| int a = GetInt(); | |
| int b = GetInt(prompt: "Please Enter Another Number: "); | |
| string operation = GetOperation(); | |
| int result = operation switch | |
| { | |
| "+" => a + b, | |
| "-" => a - b, | |
| "*" => a * b, | |
| "/" => a / b, | |
| _ => throw new NotImplementedException(), | |
| }; | |
| Console.WriteLine($"Result ({a} {operation} {b}): {result}"); | |
| Console.WriteLine(); | |
| Console.WriteLine("Press Enter To Continue..."); | |
| Console.ReadLine(); | |
| } | |
| public static int GetInt(string prompt = null) | |
| { | |
| prompt ??= "Please Enter Number: "; | |
| Console.Write(prompt); | |
| var input = Console.ReadLine(); | |
| int inputValue; | |
| bool success = int.TryParse(input, out inputValue); | |
| while (!success) | |
| { | |
| Console.WriteLine("Invalid Input. Try Again..."); | |
| Console.Write(prompt); | |
| input = Console.ReadLine(); | |
| success = int.TryParse(input, out inputValue); | |
| } | |
| return inputValue; | |
| } | |
| public static string GetOperation(string prompt = null) | |
| { | |
| prompt ??= $"Please Enter Operation({string.Join(", ", Operators)}): "; | |
| Console.Write(prompt); | |
| var input = Console.ReadLine(); | |
| bool success = Operators.Contains(input); | |
| while (!success) | |
| { | |
| Console.WriteLine("Invalid Input. Try Again..."); | |
| Console.Write(prompt); | |
| input = Console.ReadLine(); | |
| success = Operators.Contains(input); | |
| } | |
| return input; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment