2013-06-21 49 views
0

我被要求創建一個迷你和基本的購物籃,代碼正在工作,但最近for循環,我已經創建通過數組搜索跳過循環內的所有代碼。我已經提供了下面的代碼:爲什麼我的for循環跳到最後?

for (int i = 0; i < OrderItems.Count; i++) 
    { 
     //if a match is found it will add to the to the current quantity 
     if (OrderItems[i].ProductName == productName) 
      OrderItems[i].AddItem(latestValue, quantity); 

     //If no match was found in the list it will get added 
     else 
      OrderItems.Add(new OrderItem(productName, latestValue, quantity)); 
    } 

我是新相當新的C#和我可能錯過了一些東西的,可以提供

+0

does orderitems have items? – Jonesopolis

+9

'OrderItems.Count' 0? –

+7

您是否嘗試過使用調試器來查看'OrderItems'中的內容以及代碼的執行方式? –

回答

3

任何幫助,我覺得你的代碼看起來應該是這樣愚蠢的感謝:

bool found = false; 
for (int i = 0; i < OrderItems.Count; i++) 
{ 
    //if a match is found it will add to the to the current quantity 
    if (OrderItems[i].ProductName == productName) { 
     OrderItems[i].AddItem(latestValue, quantity); 
     found = true; 
    } 
} 

//If no match was found in the list it will get added 
if (! found) 
    OrderItems.Add(new OrderItem(productName, latestValue, quantity)); 

您將需要遍歷現有項目。如果找到,請更新該項目。檢查完所有物品後,才檢查是否找到物品。如果您還沒有找到該項目,請將其添加爲新項目。

您的原始代碼無效,因爲OrderItems中沒有項目,並且else語句將永遠不會執行。

如果方法實際更新項目,您可能需要考慮將方法重命名爲UpdateItem而不是AddItem

+0

我正準備發佈這,但我太慢 –

+0

感謝您的意見和 首先OrderItems是0, 其次,我已經跑過調試器幾次,然後再問在這裏,我忘了提及,在問題,我道歉dubeugger到'我

0

請檢查調試器中OrderItems的計數或打印它。在此函數/代碼執行之前發生其他錯誤是否爲零。

0

這意味着您的OrderItems爲空,並且Count屬性返回0,因此循環不會執行。如果您希望執行循環,則必須具有OrderItems。

相關問題