-1

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);
        }
    } 
}
spex5
  • 1,221
  • 4
  • 17
  • 27
  • What does the debugger tell you? – chris Jan 28 '15 at 02:56
  • System.IndexOutOfRangeException was unhandled Message: An unhandled exception of type 'System.IndexOutOfRangeException' occurred in calc.exe Additional information: Index was outside the bounds of the array. – spex5 Jan 28 '15 at 03:00
  • It should show you the exact line where this happens and what the values are. – chris Jan 28 '15 at 03:01
  • Fairly new to this. When I press q, i get 'calc.exe has stopped working' with the exception, then it asks if I want to debug. The information I gave you is what shows up in visual studio after I select debug.. Is there another way to get the exact lines and values like you said? – spex5 Jan 28 '15 at 03:08
  • 1
    It's easier to run the program in the debugger from the beginning. It's as simple as F5 instead of ctrl-F5 in Visual Studio. – chris Jan 28 '15 at 03:11
  • @GrantWinney.. I was working with this in a group and I'm actually not completely clear why we need to split them off so we can convert them to integers in the add and sub functions.. Wouldn't I just be able to set the types of my args to int in the beginning? `string ops = args[0]; int input1 = args[1]; int input2 = args[2]` – spex5 Jan 28 '15 at 03:26

1 Answers1

1

You have to check that the args has that amount of values, like you are checking args.Length > 0, also check args[1] and args[2] is set first.

You are getting and IndexOutOfRange Exception because at some point in the program running you are not giving it 3 values, perhaps in the case where you type 'q' and it is expecting 2 more values to exist but they don't. Make it so you check for existence before trying to use it or wrap it with a try catch and set a default value in the catch.

Edit: It would be something along these lines, untested:

try{
    string input1 = args[1];
}
catch (System.IndexOutOfRangeException ex)
{
    string input1 = '';
}

from https://msdn.microsoft.com/en-us/library/ms173162.aspx

You could also use a commandline arguments parser to make your app cleaner, something like this http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser

ART GALLERY
  • 540
  • 2
  • 8
  • Do you mind breaking that down a little bit with some examples of how I can use the try catch and where? I was able to debug and found that it's stopping at the `input1 = input[1] line` with the 'index was outside of the bounds of array' message. Could I do something like `if (args.Length > 0 AND condition AND condition)`? – spex5 Jan 28 '15 at 23:02