2016-06-21 56 views
-1

只要我進入while循環,程序就會拋出索引超出範圍異常,而不會獲取行和列值。 getint是獲取用戶輸入的同時確保中值的範圍的方法二維數組索引超出範圍異常

while(filled>0) 
     { 
      row = getint("row: "); 
      row--; 
      column = getint("column: "); 
      column--; 
      fields[row, column]=getint("value: "); 
      filled--; 
     } 

編輯:

static int getint(string question) 
    { 
     string temp; 
     int tempint=0; 
     while (check != 0) 
     { 
      check = 0; 
      Console.Write("\nPlease enter the {0}",question); 
      temp = Console.ReadLine(); 
      if(!int.TryParse(temp, out tempint)) 
      { 
       check++; 
      } 
      if(question.Length<14 & (tempint<1 | tempint>9)) 
      { 
       check++; 
       Console.WriteLine("Invalid Input"); 
      } 
     } 
     return tempint; 
    } 
+3

你是什麼意思的「沒有獲得行和列的價值」?我們不知道這些方法是做什麼的,也不知道「字段」的大小。請提供[mcve]。 –

+0

如果您在進入while循環時拋出異常,那麼問題可能出現在'getint()'中,但是您未包含該代碼。 – itsme86

+0

需要更多代碼。例如,這是否意味着從底部到頂部? –

回答

0

如果碼出界可以fields[row, column]只發生在您可以添加一張支票越界行和列的

row = Math.Max(row,0); 
column= Math.Max(column,0); 

row = Math.Min(fields.GetUpperBound(0), row); 
column= Math.Min(fields.GetUpperBound(1), column); 
+0

這隻會檢查下限。它更像是一張夾子而不是支票。 – itsme86

+0

謝謝,我已更新我的答案,以包括上限檢查以及 –

0

所以,錯誤是while循環,我錯過了我使用的全局變量「檢查」,當它第一次退出循環未置其所以值ti的事實我的價值被設置爲0,因此是例外。