教學課程:在 Visual Studio 中建立簡單的 C# 控制台應用程式(第 1 部分為 2)
在本教學課程中,您會使用 Visual Studio 來建立和執行 C# 控制台應用程式,並探索 Visual Studio 集成開發環境 (IDE) 的某些功能。 本教學課程是兩部分教學課程系列的第 1 部分。
在本教學課程中,您會完成下列工作:
- 建立 Visual Studio 專案。
- 建立 C# 主控台應用程式。
- 對您的應用程式進行偵錯。
- 關閉您的應用程式。
- 檢查完整的程序代碼。
在本教學課程的第 2 部分 中,您會擴充此應用程式以新增更多專案、瞭解偵錯技巧,以及參考非Microsoft套件。
先決條件
您必須安裝 Visual Studio。
如果您沒有 Visual Studio,請移至 Visual Studio 下載 免費安裝。
建立專案
若要開始,請建立 C# 應用程式專案。 項目類型隨附您需要的所有範本檔案。
開啟 Visual Studio,然後選取 [在開始視窗中建立新的專案。
在 [[建立新專案] 視窗中,從語言下拉式清單中選取 C#。 從平臺清單中選擇 [Windows],然後從專案類型清單中選擇 [控制台]。
套用語言、平臺和專案類型篩選之後,選擇 [主控台應用程式 範本],然後選取 [下一步] 。
注意
如果您沒有看到 主控台應用程式 樣本,請選擇 [[安裝更多工具和功能]。
在 Visual Studio 安裝程式中,選取 .NET Core 跨平台開發 工作負載。
在 Visual Studio 安裝程式中選取 [修改]。 系統可能會提示您儲存您的工作。 選取 [繼續] 以安裝工作負載。
返回 建立專案 程式中的步驟 2。
在 [設定新專案] 視窗中,在 [專案名稱] 方塊中輸入 計算機。 然後,選取 [下一步]。
在 [其他資訊] 視窗中,確認 [.NET Core 3.1] 出現在 [目標框架] 欄位中。 然後,選取 [建立]。
Visual Studio 會開啟您的新專案,其中包含預設 Hello World 程式代碼。 若要在編輯器中檢視它,請在 [方案總管] 視窗中選取程式代碼檔案 Program.cs,這通常是在Visual Studio 右側。
預設 Hello World 程式碼呼叫 WriteLine 方法來顯示常值字元串 Hello, World! 在主控台視窗中。 如果您按 F5,您可以在 [偵錯] 模式中執行預設程式。 在調試程式中執行應用程式之後,控制台視窗會保持開啟狀態。 按任意鍵關閉主控台視窗。
開啟 Visual Studio,然後選取 [在開始視窗中建立新的專案。
在 [[建立新專案] 視窗中,從語言下拉式清單中選取 C#。 從平臺清單中選擇 [Windows],然後從專案類型清單中選擇 [控制台]。
套用語言、平台和專案類型篩選之後,請選擇 [主控台應用程式] 範本,然後選取 [下一步] 。
注意
如果您沒有看到 主控台應用程式 樣本,請選擇 [[安裝更多工具和功能]。
在 Visual Studio 安裝程式中,選取 .NET 桌面開發 工作負載。
在 Visual Studio 安裝程式中選取 [修改]。 系統可能會提示您儲存您的工作。 選取 [繼續] 以安裝工作負載。
返回此 建立專案 程式中的步驟 2。
在 [設定新專案] 視窗中,在 [專案名稱] 方塊中輸入 Calculator,然後選取 下一步。
在 [其他資訊] 視窗中,為 [目標框架] 欄位選取 [.NET 8.0]。 然後,選取 [建立]。
Visual Studio 會開啟您的新專案,其中包含預設 Hello World 程式代碼。 若要在編輯器中檢視它,請在 [方案總管] 視窗中選取程式代碼檔案 Program.cs,這通常是在Visual Studio 右側。
單一程式碼語句會呼叫 WriteLine 方法在主控台視窗中顯示字串 Hello, World!。 如果您按 F5,您可以在 [偵錯] 模式中執行預設程式。 在調試程式中執行應用程式之後,控制台視窗會保持開啟狀態。 按任意鍵關閉主控台視窗。
注意
從 .NET 6 開始,使用控制台範本的新專案會產生與舊版不同的程序代碼。 若要深入瞭解,請參閱 新的 C# 範本產生最上層語句。
建立應用程式
在本節中,您會完成下列工作:
- 探索 C# 中的一些基本整數數學。
- 新增程式代碼以建立基本計算機應用程式。
- 偵錯應用程式以尋找並修正錯誤。
- 精簡程序代碼,使其更有效率。
探索整數數學
從 C# 中的一些基本整數數學開始。
在右窗格中,選取 [Program.cs],在程式代碼編輯器中顯示檔案。
在程式代碼編輯器中,刪除預設 Hello World 程式代碼。
具體地說,請刪除包含
Console.WriteLine("Hello World!");
的行。在其位置中,輸入下列程式代碼:
int a = 42; int b = 119; int c = a + b; Console.WriteLine(c); Console.ReadKey();
請注意,當您輸入程式代碼時,Visual Studio 中的 IntelliSense 功能會提供自動完成項目的選項。
選取 計算器 旁的綠色 開始 按鈕,以建置和執行程式,或按 F5。
開啟主控台視窗,顯示 42 + 119 的總和,161。
(選擇性) 您可以變更運算符來變更結果。 例如,您可以將程式代碼行
+
中的int c = a + b;
運算符變更為減法-
、乘法*
或除法/
。 然後,當您執行程式時,結果也會變更。關閉主控台視窗。
在 [方案總管]的右窗格中,選取 [Program.cs],在程式碼編輯器中顯示檔案。
在程式代碼編輯器中,將預設的 Hello World 程式碼替換為
Console.WriteLine("Hello World!");
。將行替換為以下程式碼:
int a = 42; int b = 119; int c = a + b; Console.WriteLine(c); Console.ReadKey();
如果您輸入程序代碼,Visual Studio IntelliSense 功能會提供自動完成項目的選項。
若要建置並執行您的應用程式,請按 F5,或選取頂端工具列中名稱旁 計算機 的綠色箭號。
主控台視窗隨即開啟,其中顯示 42 + 119 的總和,161。
關閉主控台視窗。
(選擇性) 您可以變更運算符來變更結果。 例如,您可以將程式代碼行
+
中的int c = a + b;
運算符變更為減法-
、乘法*
或除法/
。 當您執行應用程式時,結果會隨之變更。
新增程式代碼以建立計算機
繼續將更複雜的計算機程式代碼集新增至您的專案。
在程式代碼編輯器中,以下列新程式代碼取代 Program.cs 中的所有程式代碼:
using System; namespace Calculator { class Program { static void Main(string[] args) { // Declare variables and then initialize to zero. int num1 = 0; int num2 = 0; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); // Ask the user to type the first number. Console.WriteLine("Type a number, and then press Enter"); num1 = Convert.ToInt32(Console.ReadLine()); // Ask the user to type the second number. Console.WriteLine("Type another number, and then press Enter"); num2 = Convert.ToInt32(Console.ReadLine()); // Ask the user to choose an option. Console.WriteLine("Choose an option from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); // Use a switch statement to do the math. switch (Console.ReadLine()) { case "a": Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2)); break; case "s": Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2)); break; case "m": Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2)); break; case "d": Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; } // Wait for the user to respond before closing. Console.Write("Press any key to close the Calculator console app..."); Console.ReadKey(); } } }
選取 [計算機] 按鈕,或按 F5 以執行您的應用程式。
主控台視窗隨即開啟。
在控制台視窗中,遵循提示,將數位 42 和 119 加在一起。
您的應用程式看起來應該類似下列螢幕快照:
在程式代碼編輯器中,以下列新程式代碼取代 Program.cs 中的所有程式代碼:
// Declare variables and then initialize to zero. int num1 = 0; int num2 = 0; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); // Ask the user to type the first number. Console.WriteLine("Type a number, and then press Enter"); num1 = Convert.ToInt32(Console.ReadLine()); // Ask the user to type the second number. Console.WriteLine("Type another number, and then press Enter"); num2 = Convert.ToInt32(Console.ReadLine()); // Ask the user to choose an option. Console.WriteLine("Choose an option from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); // Use a switch statement to do the math. switch (Console.ReadLine()) { case "a": Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2)); break; case "s": Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2)); break; case "m": Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2)); break; case "d": Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; } // Wait for the user to respond before closing. Console.Write("Press any key to close the Calculator console app..."); Console.ReadKey();
選取 [計算機] 按鈕,或按 F5 以執行您的應用程式。
主控台視窗隨即開啟。
在控制台視窗中,遵循提示,將數位 42 和 119 加在一起。
您的應用程式看起來應該類似下列螢幕快照:
新增十進位功能
現在,調整程式代碼以新增更多功能。
目前的計算機應用程式只接受並傳回整數。 例如,如果您執行應用程式,並將數位 42 除以數位 119,則結果為零,這不是確切的結果。
若要修正程式代碼,藉由處理小數點來改善精確度:
從 Visual Studio 編輯器中的 Program.cs,按 ctrl +,以開啟 [尋找及取代] 控件。
在控件中輸入 int,然後在 [取代] 字段中輸入 float。
選取控件中 Match 大小寫 和 比對整字 的圖示,或按 Alt+C,並 Alt+W。
選取 [取代所有] 圖示,或按 Alt+A 來執行搜尋並取代。
再次執行計算機應用程式,並將數位 42 除以數位 119。
應用程式現在會傳回十進位數,而不是零。
現在應用程式可以產生十進位結果。 再調整一些程式代碼,讓應用程式也可以計算小數點。
使用 Find 和 Replace 控制件,將
float
變數的每個實例變更為double
,並將Convert.ToInt32
方法的每個實例變更為Convert.ToDouble
。執行計算機應用程式,並將數字 42.5 除以數字 119.75。
應用程式現在接受十進位值,並傳回較長的十進位數位做為其結果。
在 [修改程式碼] 區段中,您可以減少結果中的小數位數。
對應用程式進行偵錯
您改善了基本的計算機應用程式,但您的應用程式尚未處理例外狀況,例如使用者輸入錯誤。 例如,如果用戶嘗試除以零或輸入非預期的字元,應用程式可能會停止運作、傳回錯誤或傳回非數值結果。
讓我們一步步檢視一些常見的使用者輸入錯誤,若在除錯工具中出現,便在程式代碼中進行修正。
提示
如需有關偵錯器及其運作方式的詳細資訊,請參閱 初步了解 Visual Studio 偵錯器。
修正 除以零 的錯誤
如果您嘗試將數位除以零,控制台應用程式可能會凍結,然後在程式碼編輯器中顯示錯誤。
注意
有時候應用程式不會凍結,而且調試程式不會顯示零除錯誤。 相反地,應用程式可能會傳回意想不到的非數值結果,例如無限符號。 下列程式代碼修正仍然適用。
讓我們變更程式代碼來處理此錯誤。 在 Program.cs中,將 case "d":
的程式代碼取代為下列程式代碼:
// Ask the user to enter a non-zero divisor until they do so.
while (num2 == 0)
{
Console.WriteLine("Enter a non-zero divisor: ");
num2 = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
break;
取代程式代碼之後,使用 switch
語句的 區段看起來應該類似下列螢幕快照:
現在,當您將任何數位除以零時,應用程式會要求另一個數位,並持續詢問,直到您提供非零的數字為止。
修正 格式 錯誤
如果您在應用程式預期數位字元時輸入字母字元,應用程式會凍結。 Visual Studio 會在程式碼編輯器中顯示程式中的問題。
若要防止此例外狀況,您可以重構您先前輸入的程序代碼。
修改程序代碼
您可以分割應用程式成兩個類別:program
和 Calculator
,而不是依賴 Program
類別來處理所有程序代碼。
Calculator
類別會處理大部分的計算工作,而 Program
類別會處理使用者介面和錯誤處理工作。
讓我們開始吧。
在 Program.cs中,刪除所有專案,並新增下列新
Calculator
類別:class Calculator { public static double DoOperation(double num1, double num2, string op) { double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error. // Use a switch statement to do the math. switch (op) { case "a": result = num1 + num2; break; case "s": result = num1 - num2; break; case "m": result = num1 * num2; break; case "d": // Ask the user to enter a non-zero divisor. if (num2 != 0) { result = num1 / num2; } break; // Return text for an incorrect option entry. default: break; } return result; } }
此外,新增
Program
類別,如下所示:class Program { static void Main(string[] args) { bool endApp = false; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); while (!endApp) { // Declare variables and set to empty. string numInput1 = ""; string numInput2 = ""; double result = 0; // Ask the user to type the first number. Console.Write("Type a number, and then press Enter: "); numInput1 = Console.ReadLine(); double cleanNum1 = 0; while (!double.TryParse(numInput1, out cleanNum1)) { Console.Write("This is not valid input. Please enter a numeric value: "); numInput1 = Console.ReadLine(); } // Ask the user to type the second number. Console.Write("Type another number, and then press Enter: "); numInput2 = Console.ReadLine(); double cleanNum2 = 0; while (!double.TryParse(numInput2, out cleanNum2)) { Console.Write("This is not valid input. Please enter a numeric value: "); numInput2 = Console.ReadLine(); } // Ask the user to choose an operator. Console.WriteLine("Choose an operator from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); string op = Console.ReadLine(); try { result = Calculator.DoOperation(cleanNum1, cleanNum2, op); if (double.IsNaN(result)) { Console.WriteLine("This operation will result in a mathematical error.\n"); } else Console.WriteLine("Your result: {0:0.##}\n", result); } catch (Exception e) { Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message); } Console.WriteLine("------------------------\n"); // Wait for the user to respond before closing. Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: "); if (Console.ReadLine() == "n") endApp = true; Console.WriteLine("\n"); // Friendly linespacing. } return; } }
選取 [計算機] 按鈕,或按 F5 以執行您的應用程式。
遵循提示,並將數字 42 除以數字 119。 您的結果看起來應該類似下列螢幕快照:
您現在可以執行更多計算,直到您選擇關閉主控台應用程式為止。 結果中小數位數也較少。 如果您輸入不正確的字元,您會收到適當的錯誤回應。
修改程序代碼
您可以分割應用程式成兩個類別:program
和 Calculator
,而不是依賴 Program
類別來處理所有程序代碼。
Calculator
類別會處理大部分的計算工作,而 Program
類別會處理使用者介面和錯誤處理工作。
讓我們開始吧。
在 Program.cs中,刪除所有專案,並新增下列新
Calculator
類別:class Calculator { public static double DoOperation(double num1, double num2, string op) { double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error. // Use a switch statement to do the math. switch (op) { case "a": result = num1 + num2; break; case "s": result = num1 - num2; break; case "m": result = num1 * num2; break; case "d": // Ask the user to enter a non-zero divisor. if (num2 != 0) { result = num1 / num2; } break; // Return text for an incorrect option entry. default: break; } return result; } }
此外,新增
Program
類別,如下所示:class Program { static void Main(string[] args) { bool endApp = false; // Display title as the C# console calculator app. Console.WriteLine("Console Calculator in C#\r"); Console.WriteLine("------------------------\n"); while (!endApp) { // Declare variables and set to empty. // Use Nullable types (with ?) to match type of System.Console.ReadLine string? numInput1 = ""; string? numInput2 = ""; double result = 0; // Ask the user to type the first number. Console.Write("Type a number, and then press Enter: "); numInput1 = Console.ReadLine(); double cleanNum1 = 0; while (!double.TryParse(numInput1, out cleanNum1)) { Console.Write("This is not valid input. Please enter a numeric value: "); numInput1 = Console.ReadLine(); } // Ask the user to type the second number. Console.Write("Type another number, and then press Enter: "); numInput2 = Console.ReadLine(); double cleanNum2 = 0; while (!double.TryParse(numInput2, out cleanNum2)) { Console.Write("This is not valid input. Please enter a numeric value: "); numInput2 = Console.ReadLine(); } // Ask the user to choose an operator. Console.WriteLine("Choose an operator from the following list:"); Console.WriteLine("\ta - Add"); Console.WriteLine("\ts - Subtract"); Console.WriteLine("\tm - Multiply"); Console.WriteLine("\td - Divide"); Console.Write("Your option? "); string? op = Console.ReadLine(); // Validate input is not null, and matches the pattern if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]")) { Console.WriteLine("Error: Unrecognized input."); } else { try { result = Calculator.DoOperation(cleanNum1, cleanNum2, op); if (double.IsNaN(result)) { Console.WriteLine("This operation will result in a mathematical error.\n"); } else Console.WriteLine("Your result: {0:0.##}\n", result); } catch (Exception e) { Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message); } } Console.WriteLine("------------------------\n"); // Wait for the user to respond before closing. Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: "); if (Console.ReadLine() == "n") endApp = true; Console.WriteLine("\n"); // Friendly linespacing. } return; } }
注意
最好針對輸入字串使用具可空性的類型(搭配
?
符號),因為System.Console.ReadLine
傳回一個 可空性參考型別。選取 [計算機] 按鈕,或按 F5 以執行您的應用程式。
遵循提示,並將數字 42 除以數字 119。 您的結果看起來應該類似下列螢幕快照:
您現在可以執行更多計算,直到您選擇關閉主控台應用程式為止。 結果中小數位數也較少。 如果您輸入不正確的字元,您會收到適當的錯誤回應。
關閉應用程式
如果您尚未這麼做,請關閉計算機應用程式。
在 Visual Studio 中關閉 [] [輸出] 窗格。
在 Visual Studio 中,按 Ctrl Ctrl+S 以儲存您的應用程式。
新增 Git 原始檔控制
既然您已有應用程式,您可能想要將它新增至 Git 存放庫。 Visual Studio 透過可直接從 IDE 使用的 Git 工具,使該過程變得簡單。
提示
Git 是最廣泛使用的新式版本控制系統。 無論您是專業開發人員,還是正在學習如何撰寫程式代碼,Git 都非常有用。 如果您不熟悉 Git,https://git-scm.com/
網站是很好的起點。 您可以找到速查表、熱門的在線書籍和 Git 基本概念影片。
若要將程式代碼與 Git 產生關聯,請先建立程式代碼所在的新 Git 存放庫:
在 Visual Studio 右下角的狀態欄中,選取 [[新增至原始檔控制],然後選取 [Git]。
在 [[建立 Git 存放庫] 對話框中,登入 GitHub:
存放庫名稱會根據您的資料夾位置自動填入。 根據預設,您的新存放庫是私人的,這表示您是唯一可以存取它的人員。
提示
無論您的存放庫是公用還是私人,最好有安全地儲存在 GitHub 上的程式代碼遠端備份。 即使您未與小組合作,遠端存放庫仍可讓您從任何電腦使用您的程式代碼。
選取 建立 和 推送。 建立存放庫之後,您會在狀態列中看到狀態詳細數據:
在 Visual Studio 中使用 Git 動作
以下是 Visual Studio 狀態列中可用的 Git 動作簡短摘要:
向上/向下 箭號會顯示您目前分支中的傳出/傳入提交數量。 您可以使用此圖示來拉取任何傳入的提交或推送任何傳出的提交。
若要檢視特定提交,請選取 向上/向下箭頭,然後選取 [檢視傳出/傳入]。
鉛筆 會顯示程式代碼未提交的變更數目。 您可以選取此圖示,在 [Git 變更] 視窗中檢視這些變更。
[Git] 功能表提供檔案上存放庫動作的工具。 您可以 在 Visual Studio中使用 git fetch、pull、push 和 sync 進行版本控制。
如需如何搭配應用程式使用 Git 的詳細資訊,請參閱 Visual Studio 中的關於 Git。
檢閱:程序代碼完成
在本教學課程中,您已對計算機應用程式進行許多變更。 應用程式現在會更有效率地處理計算資源,並處理大部分的使用者輸入錯誤。
以下是完整的程序代碼,全部放在一個位置:
class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
{
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
}
break;
// Return text for an incorrect option entry.
default:
break;
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
}
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
}
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string op = Console.ReadLine();
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
}
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
}
return;
}
}
class Calculator
{
public static double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.
// Use a switch statement to do the math.
switch (op)
{
case "a":
result = num1 + num2;
break;
case "s":
result = num1 - num2;
break;
case "m":
result = num1 * num2;
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
}
break;
// Return text for an incorrect option entry.
default:
break;
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
while (!endApp)
{
// Declare variables and set to empty.
// Use Nullable types (with ?) to match type of System.Console.ReadLine
string? numInput1 = "";
string? numInput2 = "";
double result = 0;
// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();
double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput1 = Console.ReadLine();
}
// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();
double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter a numeric value: ");
numInput2 = Console.ReadLine();
}
// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
string? op = Console.ReadLine();
// Validate input is not null, and matches the pattern
if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]"))
{
Console.WriteLine("Error: Unrecognized input.");
}
else
{
try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
}
}
Console.WriteLine("------------------------\n");
// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;
Console.WriteLine("\n"); // Friendly linespacing.
}
return;
}
}
下一步
繼續進行本教學課程的第二個部分: