Visual Studio 2019教程:創(chuàng)建一個(gè)簡單的C#控制臺應(yīng)用程序(二)
在上篇中,介紹了使用VS 2019創(chuàng)建一個(gè)簡單的控制臺應(yīng)用程序、探索整數(shù)數(shù)學(xué)、添加代碼創(chuàng)建計(jì)算器等內(nèi)容。本文承接上文內(nèi)容,繼續(xù)為大家介紹使用VS 2019創(chuàng)建一個(gè)簡單的C??刂婆_應(yīng)用程序的其他步驟。
向計(jì)算器添加功能
通過調(diào)整代碼來添加更多功能。
加小數(shù)
計(jì)算器應(yīng)用程序當(dāng)前接受并返回整數(shù)。但是,如果我們添加允許使用小數(shù)的代碼,它將更加精確。
如下面的屏幕截圖所示,如果您運(yùn)行應(yīng)用程序,然后將數(shù)字42除以119,則結(jié)果為0(零),這是不正確的。
簡單修改代碼就可以處理小數(shù):
1按Ctrl + F打開“Find and Replace”控件。
2、將int變量的每個(gè)實(shí)例更改為float。
確保在“Find and Replace”控件中切換“Match case (Alt+C)”和“Match whole word (Alt+W) ” 。
3、再次運(yùn)行計(jì)算器應(yīng)用,然后將數(shù)字42除以119。
請注意,應(yīng)用程序現(xiàn)在返回的是十進(jìn)制數(shù)字而不是零。
但是,該應(yīng)用程序僅產(chǎn)生十進(jìn)制結(jié)果?,F(xiàn)在,繼續(xù)對代碼進(jìn)行一些調(diào)整,讓應(yīng)用程序也可以計(jì)算小數(shù)。
1、使用“Find and Replace”控件(Ctrl + F)將float變量的每個(gè)實(shí)例更改為double,并將Convert.ToInt32方法的每個(gè)實(shí)例更改為Convert.ToDouble。
2、運(yùn)行計(jì)算器應(yīng)用,然后將數(shù)字42.5除以119.75。
請注意,該應(yīng)用程序現(xiàn)在接受十進(jìn)制值,并返回一個(gè)較長的十進(jìn)制數(shù)字作為結(jié)果。
調(diào)試應(yīng)用
我們在基本的計(jì)算器應(yīng)用程序上進(jìn)行了改進(jìn),但尚未設(shè)置故障保險(xiǎn)柜來處理諸如用戶輸入錯(cuò)誤之類的異常。
例如,如果您試圖將一個(gè)數(shù)字除以0,或者在應(yīng)用程序需要一個(gè)數(shù)字字符時(shí)輸入一個(gè)alpha字符(反之亦然),應(yīng)用程序?qū)⑼V构ぷ鞑⒎祷匾粋€(gè)錯(cuò)誤。
接下來,我們?yōu)g覽幾個(gè)常見的用戶輸入錯(cuò)誤,在調(diào)試器中找到它們,并在代碼中修復(fù)錯(cuò)誤。
修復(fù)“被零除”錯(cuò)誤
當(dāng)您嘗試將數(shù)字除以零時(shí),控制臺應(yīng)用程序?qū)⑼V惯\(yùn)行。然后,Visual Studio會提示代碼編輯器中的問題。
要處理此錯(cuò)誤,只需更改幾個(gè)代碼:
1、刪除直接出現(xiàn)在的代碼case "d":和注釋之間的代碼// Wait for the user to respond before closing。
2、將其替換為以下代碼:
// 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.ToInt32(Console.ReadLine()); } Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2)); break; }
添加代碼后,帶有switch語句的部分應(yīng)類似于以下屏幕截圖:
現(xiàn)在,當(dāng)您將任何數(shù)字除以零時(shí),應(yīng)用程序?qū)⑻崾灸鷵Q一個(gè)數(shù)字,直到您提供非零的數(shù)字。
修復(fù)“格式”錯(cuò)誤
如果在應(yīng)用程序要求輸入數(shù)字字符時(shí)輸入字母字符(反之亦然),則控制臺應(yīng)用程序?qū)⑼V惯\(yùn)行。然后,Visual Studio會提示代碼編輯器中的問題。
要解決此錯(cuò)誤,必須重構(gòu)我們先前輸入的代碼。
修改代碼
我們將應(yīng)用分為兩類:Calculator和Program,而不是依賴程序類來處理所有代碼。
Calculator類將處理大量的計(jì)算工作,而所述Program類將處理用戶界面和捕獲錯(cuò)誤的工作。
1、刪除以下代碼塊之后的所有內(nèi)容:
using System; namespace Calculator {
2、添加一個(gè)新Calculator類,如下所示:
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; } }
3、然后,添加一個(gè)新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 an integer 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 an integer 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; } }
4、選擇Calculator運(yùn)行程序,或按F5。
5、按照提示將數(shù)字42除以119。應(yīng)用程序應(yīng)類似于以下屏幕截圖:
請注意,在選擇關(guān)閉控制臺應(yīng)用程序之前,可以選擇輸入更多方程式。并且,我們還減少了結(jié)果中的小數(shù)位數(shù)。
關(guān)閉應(yīng)用程序
1、如果尚未執(zhí)行此操作,請關(guān)閉計(jì)算器應(yīng)用程序。
2、在Visual Studio中關(guān)閉“Output”窗格。
3、在Visual Studio中,按Ctrl + S保存應(yīng)用程序。
4、關(guān)閉Visual Studio。
代碼完成
在本教程中,我們對計(jì)算器應(yīng)用程序進(jìn)行了很多更改。該應(yīng)用程序現(xiàn)在可以更有效地處理計(jì)算資源,并且可以處理大多數(shù)用戶輸入錯(cuò)誤。
以下是涉及的所有代碼:
using System; namespace Calculator { 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 an integer 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 an integer 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; } } }
以上就是本教程的所有內(nèi)容。下一節(jié),將介紹如何在Visual Studio中使用C#和ASP.NET Core,歡迎持續(xù)關(guān)注。
想要獲取 Visual Studio 更多資源或正版授權(quán)的伙伴請聯(lián)系【慧都客服】領(lǐng)取
慧都16周年·技術(shù)服務(wù)月,軟件商城優(yōu)惠券不限量免費(fèi)放送,購物立減服務(wù)升級,享受折上折>>>