2017-02-18 87 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並且應該解決問題!