I see several answers to this error in other threads, but I'd like to know how this applies to my code specifically. You input 2 parameters and it will add or subtract them. (For example: calc.exe add 2 2) When I press q to quit the program, I get the following:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array at Calc.Calc.Main(String[] args)
Can someone explain where I went wrong in the code and how to fix it? Thanks.
using System;
namespace Calc
{
public class Calc
{
// Calc app
/// <summary>
/// Calc app:
/// Actions: add, sub, multi, div
/// Param: calc action value 1, value 2
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
if (args.Length > 0)
{
string ops = args[0];
string input1 = args[1];
string input2 = args[2];
while (ops != "q")
{
Console.WriteLine("Ready");
if (ops == "add")
{
Add(input1, input2);
}
else if (ops == "sub")
{
Sub(input1, input2);
}
else
{
Console.WriteLine("Operation not supported: [" + ops + "]");
Console.WriteLine("Try again.");
}
string[] inputs = Console.ReadLine().Split(' ');
ops = inputs[0];
input1 = inputs[1];
input2 = inputs[2];
}
// exit the app
return;
}
// no argument was provided
Console.WriteLine("Show help!");
Console.ReadKey();
} //main end
public static void Add(string val1, string val2)
{
int num1 = Convert.ToInt32(val1);
int num2 = Convert.ToInt32(val2);
Console.WriteLine("Result: {0} ", num1 + num2);
}
public static void Sub(string val1, string val2)
{
int num1 = Convert.ToInt32(val1);
int num2 = Convert.ToInt32(val2);
Console.WriteLine("Result: {0} ", num1 - num2);
}
}
}