我希望这是一件小事,而不是一个大问题。我正在编写一个程序(通过书籍自学),它将要求一个运算符,然后是一组数字,然后应用运算符来获得结果。该程序没有提示我输入数字并假定一个空数组。我想我明白出了什么问题,只是不知道如何重新编码,以便它会要求我将数字输入数组。
我很好奇的另一件事是,如果运算符无效,我可以强制程序在类代码的第一个开关中退出吗?我找到了 Application.Exit() 但这似乎只适用于 WinForms。是否有等效的 C# 代码?
我的主要方法如下:
static void Main(string[] args)
{
MathMethodClass mathMethods = new MathMethodClass();
int[] intArray = new int[] { };
Console.Write("Choose an Operator + or *: ");
string whichOp = Console.ReadLine();
Console.WriteLine("Thank you. You chose {0}.", mathMethods.OperatorName(whichOp));
Console.WriteLine("Please enter an array of numbers: ");
for (int i=0;i<intArray.Length;i++)
{
intArray[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Thank you. You entered the numbers {0}", intArray);
Console.WriteLine("The answer is: {0}.", mathMethods.MathMethod(whichOp, intArray));
Console.ReadLine();
}
我的班级如下:
class MathMethodClass
{
public string OperatorName(string whichOp)
{
switch (whichOp)
{
case "+":
whichOp = "addition";
break;
case "*":
whichOp = "multiplication";
break;
default:
Console.WriteLine("Error: Unknown Operator. Exiting ...");
Console.ReadLine();
break;
}
return whichOp;
}
public int MathMethod(string whichOp, params int[] theNums)
{
int theAnswer = 0;
switch (whichOp)
{
case "+":
for (int ct = 0; ct < theNums.Length; ct++)
{
theAnswer += theNums[ct];
}
break;
case "*":
for (int ct = 0; ct < theNums.Length; ct++)
{
theAnswer *= theNums[ct];
}
break;
default:
Console.WriteLine("Error. Something went wrong in the MathMethod. Exiting ...");
Console.ReadLine();
break;
}
return theAnswer;
}
}
让我知道哪里出错的任何帮助都会很棒。
谢谢。