-3
public class LetterArray 
{
internal static string[] Alphabet() {
    var letterValues = new string[25];

    letterValues[0] = "A";
    letterValues[1] = "B";
    letterValues[2] = "C";
    letterValues[3] = "D";
    letterValues[4] = "E";
    letterValues[5] = "F";
    letterValues[6] = "G";
    letterValues[7] = "H";
    letterValues[8] = "I";
    letterValues[9] = "J";
    letterValues[10] = "K";
    letterValues[11] = "L";
    letterValues[12] = "M";
    letterValues[13] = "N";
    letterValues[14] = "O";
    letterValues[15] = "P";
    letterValues[16] = "Q";
    letterValues[17] = "R";
    letterValues[18] = "S";
    letterValues[19] = "T";
    letterValues[20] = "U";
    letterValues[21] = "V";
    letterValues[22] = "W";
    letterValues[23] = "X";
    letterValues[24] = "Y";
    letterValues[25] = "Z";

    return letterValues;
}
}


public class Decipher
{
public static void Main() //Main method
{
    int res = 34;
    string[] letterValues = LetterArray.Alphabet();
    //Create for loop that runs through every possible shift value
    for (int shift = 0; shift <= 25; shift++) {
        Console.WriteLine("\nShift Value = " + shift + ": ");
    // For each character in the text file
        foreach (var ch in ReadText.cipherTxt()) {
            if (ch == ' ') {
            } else {
                for (int i = 0; i <= 25; i++) {
                    if ((ch.ToString().ToUpper()) == letterValues[i]) {
                        res = i;
                    }
                }

                if (shift > res) {
                    Console.WriteLine(letterValues[26 - (shift - res)][0]);
                } else {
                    Console.WriteLine(letterValues[res - shift][0]);
                }
            }
        }                    
    }
 }

System.IndexOutOfRangeException: Index was outside the bounds of the array.

Not really sure why this is occurring, I've tried looking through the code to find things listed outside the range of the array but can't see anything? Was hoping someone could enlighten me on what I'm doing wrong or how I can sort this error out. It says it's occurring somewhere in LetterArray.Alphabet and Decipher.Main.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Josh
  • 61
  • 7

1 Answers1

2

var letterValues = new string[25] creates an array with 25 positions.

When you do letterValues[25] = "Z"; you are accessing the position 26, since it starts from 0.

So you just need to change your array size to 26.

var letterValues = new string[26]
Jorgel
  • 920
  • 3
  • 14
  • 28