2017-02-18 27 views
0

我正在尝试做一些小学作业。所以对于输入来说,它会是像迈克这样的任何名字。IndexOutOfRangeException,但没有超出范围

但我们需要检查名称是否实际上是英文的。如果是,则输出将是“你好,姓名” 我通过检查每个字母的ASCII码并查看它是否实际上是英文字母ASCII码的一部分来检查英文字母。还使用一组布尔值来做到这一点。

我的代码如下:

string name = Console.ReadLine(); 
bool[] isEnglish = new bool[name.Length]; 
int num = 0; 

for (int i = 0; i<=name.Length;i++) 
{ 
     for (int ii = 65;ii<=122;ii++) 
     { 
      if(name[i] == (char)ii) 
      { 
       isEnglish[i] = true; 

       break; 
      } 
     } 
} 

for (int iii = 0; iii<=name.Length;iii++) 
{ 
    if (isEnglish[iii] == true) 
    { 
     num++; 
    }   
} 

if(num == name.Length) 
Console.WriteLine("Hello, {0}!", name); 

else 
Console.WriteLine("name isn't in English"); 

和我得到错误:

Unhandled Exception: 
System.IndexOutOfRangeException: Index was outside the bounds of the array. 
    at Solution.Main (System.String[] args) [0x00024] in solution.cs:14 
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array. 
    at Solution.Main (System.String[] args) [0x00024] in solution.cs:14 

所以误差为14行?我看不出有什么错线14.我很为难

+0

我实际上没有复制'main'函数和usings',所以减去它将会是第8行。(14-6) –

+0

您可以使用一个称为调试的很酷功能。我们也不知道哪一行是第14行。 – mybirthname

+0

阅读[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。哦,一个长度为五的数组有索引0,1,2,3,4。 –

回答

4

更改此:

for(int i = 0; i <= name.Length; i++) 
//and 
for (int ii = 65; ii <= 122; ii++) 
//and 
for(int iii = 0; iii <= name.Length; iii++) 

这样:

for(int i = 0; i < name.Length; i++) 
//and 
for (int ii = 65; ii < 122; ii++) // but this case may work for you without changes 
//and 
for(int iii = 0; iii < name.Length; iii++) 

索引从0Length - 1(总是比Length下启动),但是您的索引是从0Length(而不是Length - 1) - 您应该将<=更改为<

0

绝对有一个IndexOutOfRangeException,当i == name.Length。注意基于零的索引。

1

因为您从0循环到数组的长度,所以您要走出界限。如果数组有3个元素,则其长度将为3,但其索引将为0,1,2。 而你正在循环从0到长度,所以你的索引变为0,1,2 3. 你需要循环从0到length-1并且应该解决问题!