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
:索引超出了数组的范围。
我不确定为什么会发生这种情况,我已经尝试查看代码以查找列在数组范围之外的内容但却看不到任何内容?希望有人可以告诉我我做错了什么或如何解决这个错误。它说它发生在LetterArray.Alphabet和Decipher.Main的某个地方。
答案 0 :(得分:2)
extends
创建一个包含25个位置的数组。
执行var letterValues = new string[25]
时,您正在访问位置26,因为它从0开始。
所以你只需要将数组大小更改为26.
letterValues[25] = "Z";