I am trying to write a C# program that will convert Roman numbers to Integer.
I get index outside of bounds of the array error when I try short inputs.
When I try long input like = "MCMXIV" (it equals to 1994) I get exactly 1994 as result.
But when I try shorter input like "III", I get Index outside of bounds of the array error.
Can you check my code and tell me where did I make mistake? Thanks.
using System;
public class Program
{
public static void Main()
{
Console.Write("Input:");
string s = Console.ReadLine();
int print = RomanToInt(s);
Console.WriteLine($"Result is: {print}");
static int RomanToInt(string s)
{
int [] decimalValues = new int[7] { 1, 5, 10, 50, 100, 500, 1000};
int [] inputValues = new int[s.Length];
for (int i = 0; i < s.Length; i++)
{
if (s[i] == 'I')
{
inputValues[i] = decimalValues[0];
}
else if (s[i] == 'V')
{
inputValues[i] = decimalValues[1];
}
else if (s[i] == 'X')
{
inputValues[i] = decimalValues[2];
}
else if (s[i] == 'L')
{
inputValues[i] = decimalValues[3];
}
else if (s[i] == 'C')
{
inputValues[i] = decimalValues[4];
}
else if (s[i] == 'D')
{
inputValues[i] = decimalValues[5];
}
else if (s[i] == 'M')
{
inputValues[i] = decimalValues[6];
}
}
int [] inputValuesAfter = new int[s.Length];
for (int i = 0; i < inputValues.Length; i++)
{
if (inputValues[i] >= inputValues[i+1])
{
inputValuesAfter[i] = inputValues[i];
}
else if (inputValues[i] < inputValues[i+1])
{
inputValuesAfter[i] = inputValues[i+1] - inputValues[i];
i++;
}
}
int result = 0;
for (int i = 0; i < (inputValuesAfter.Length); i++)
{
result += inputValuesAfter[i];
}
return result;
}
}
}