I am hoping this is something small and not a big issue. I am coding a program (Self teaching via book) which will ask for an operator, then an array of numbers then apply the operator to get a result. The program isn’t prompting me for numbers and assumes an empty array. I think I understand what is going wrong, just not how to recode it so that it will ask me to enter the numbers into the array.
The other thing I am curious about is can I force the program to exit in the first switch of the class code if the Operator is not valid? I found Application.Exit() but that only seems to work for WinForms. Is there a C# code equivalent?
My Main method is as follows:
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();
}
And my Class is as follows:
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;
}
}
Any assistance in letting me know where I am going wrong would be great.
Thanks.
You need to specify an array size, you are currently creating an empty array. Define it with some size like:
Or the better approach would be to ask the user for the array size. Add the following code before your for loop
In your original code you are specifying the array of
0size withint[] intArray = new int[] { };and later in your loop, you are checking it against the length and thus not getting into the loop. That is why you are having problem. Other than that code seems to be fine. A much better approach would be to use int.TryParse instead ofint.Parse, so that you can check for validintinput.