Calculator Application with Library 2.1.2
A simple library for performing basic arithmetic operations with application
Loading...
Searching...
No Matches
CalculatorCli.cs
Go to the documentation of this file.
1namespace CalculatorLibrary {
2
20public static class CalculatorCli {
22 public const string UsageText = "Usage: CalculatorApp <add|subtract|multiply|divide> <a> <b>";
23
38 public static string Run(string[] args) {
39 if (args.Length != 3) {
40 throw new ArgumentException($"Expected 3 arguments (operation, a, b) but got {args.Length}. {UsageText}");
41 }
42
43 string operation = args[0].Trim().ToLowerInvariant();
44
45 if (!int.TryParse(args[1], out int a)) {
46 throw new ArgumentException($"'{args[1]}' is not a valid 32-bit integer for <a>. {UsageText}");
47 }
48
49 if (!int.TryParse(args[2], out int b)) {
50 throw new ArgumentException($"'{args[2]}' is not a valid 32-bit integer for <b>. {UsageText}");
51 }
52
53 var calculator = new Calculator();
54
55 int result = operation switch {
56 "add" => calculator.Add(a, b),
57 "subtract" => calculator.Subtract(a, b),
58 "multiply" => calculator.Multiply(a, b),
59 "divide" => calculator.Divide(a, b),
60 _ => throw new ArgumentException($"Unknown operation '{args[0]}'. {UsageText}"),
61 };
62
63 return $"{a} {operation} {b} = {result}";
64 }
65
72 public static string RunDemo() {
73 var calculator = new Calculator();
74 var lines = new System.Text.StringBuilder();
75 lines.AppendLine("Calculator Application Running (no arguments given, showing the built-in demo)...");
76 lines.AppendLine($"2 add 2 = {calculator.Add(2, 2)}");
77 lines.AppendLine($"2 multiply 2 = {calculator.Multiply(2, 2)}");
78 lines.AppendLine($"2 subtract 2 = {calculator.Subtract(2, 2)}");
79 lines.AppendLine($"2 divide 2 = {calculator.Divide(2, 2)}");
80 lines.Append(UsageText);
81 return lines.ToString();
82 }
83}
84}
Parses and runs the calculator's command-line arguments.
const string UsageText
The usage line shown when the arguments cannot be parsed.
static string RunDemo()
Runs a small built-in demonstration that exercises every operation once, used when the application is...
static string Run(string[] args)
Parses args as <operation> <a> <b> and returns a line of text describing the result.
Performs basic arithmetic operations on integers.
Definition Calculator.cs:11