这是我为计算器编写的代码,没有任何教程,我想保持这种方式,所以我想想象和创建自己的代码,因为我只是一个初学者。
Console.Title = "My Epic Calculator !";
var numOne = "";
var numTwo = "";
var term = "";
var answer = 0;
Console.WriteLine("Hello there, welcome to my calculator !nIt can calculate everything. Come on, try it !");
Console.WriteLine("Enter your first number below.");
numOne = Console.ReadLine();
if (numOne == "")
{
Console.WriteLine("Please enter a valud number");
}
int firstTerm = int.Parse(numOne);
Console.WriteLine("Now enter your second number.");
numTwo = Console.ReadLine();
int secondTerm = int.Parse(numTwo);
Console.WriteLine("Choose your mathematical option: x, /, + and -");
term = Console.ReadLine();
if (term == "x")
{
answer = firstTerm * secondTerm;
}
else if (term == "/")
{
answer = firstTerm / secondTerm;
}
else if (term == "+")
{
answer = firstTerm + secondTerm;
}
else if (term == "-")
{
answer = firstTerm - secondTerm;
}
Console.WriteLine($"And your answer is {answer}, see it's pretty cool huh!");
Console.ReadKey();
如您所见,如果用户在文本中输入您希望写入的数字(例如numOne/numTwo),则它缺少异常。不幸的是,我不知道如何解决这个问题,有人能帮忙吗?谢谢你。我也希望有一些技巧来优化我的代码,因为我知道这是非常混乱的,我的成堆的If。
int numOneIntValue= 0; if (!int.TryParse(numOne, out numOneIntValue)) { Console.WriteLine("numOne is not a number!"); } int numTwoIntValue= 0 ; if (!int.TryParse(numTwo , out numTwoIntValue)) { Console.WriteLine("numTwo is not a number!"); }