在不超出数组范围的情况下获取IndexOutOfRangeException

时间:2015-05-07 06:27:46

标签: c# encryption indexoutofboundsexception

所以我有以下代码使用orgTxtrndTxt创建加密字符串,当我在Visual Studio中调试代码时,我在第二个for循环中收到IndexOutOfRangeException错误。

我用断点检查索引的值,它似乎完全在范围内,任何人都知道问题是什么? 如果需要更多信息来帮助解决此错误,请留下我的评论。

//variables
    string scrtTxt = null;
    string rndTxt = null;
    string orgTxt = reader.ReadToEnd();

//assigning random a string from key (set of all capital letters) to rndTxt
for (int i = 0; i < fileInfo.Length; i++) 
        {
             rndTxt += key[random.Next(0, key.Length)]; 
        }

//generating the encrypted message scrtTxt
 int j = 0;
 for (int i = 0; i < fileInfo.Length; i++)
       {
            if ((orgTxt[i] + rndTxt[j] - 'A') <= 'Z' && (orgTxt[i] + rndTxt[j] - 'A') >= 'A')
                    scrtTxt += Convert.ToChar((orgTxt[i] + rndTxt[j] - 'A'));

            if ((orgTxt[i] + rndTxt[j] - 'A') > 'Z')
                    scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);//IndexOutOfRangeException error here

            j = j + 1 == rndTxt.Length ? 0 : j + 1;
       }

1 个答案:

答案 0 :(得分:5)

您正在从这行代码中的scrtTxt数组中读取数据。

scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);

这是你想要做的,还是应该是orgTxt或rndTxt?