2012-01-15 32 views
0

當我試圖在數組中放置一個值時,我得到了一個不尋常的結果。 我有一個簡單的類結果{int分數,很長的時間,字符串ID}的數組表[} 意圖是有一種排行榜。 我的代碼愉快地找到正確的位置,插入一個新的分數,如果它是在頂部10數組訪問產生不需要的結果

int ix = 0; 
    int jx = 10; // 
    while (ix < jx) 
    { 
     if (points > sTable[ix].points) 
     { 
      // score is higher move records down 
      for (jx = mNumRecords - 1; jx >ix ; jx--) 
      { 
       sTable[jx] = sTable[jx -1]; 
      } 
      //now add new score 
      sTable[ix].score = score; // all good until here 
      sTable[ix].time = time; 


     } 

     ix++;   
    } 

問題是,當我嘗試使用穩定[IX] .score =得分插入分數;

將值寫入sTable [ix] .score和sTable [ix +1] .score。

它是可重複的,它發生在ix的任何值處,我單步穿過代碼,並且據我所知只能執行一次。

有沒有人見過這個?

+0

哦,是的。我們都曾經見過。我們都爲它拍了額頭。 :) Binyamin在他的答案中有解決方案。 :) – 2012-01-15 05:26:31

回答

0

這是因爲您將對象引用複製到數組中的下一個元素。您應該複製的值,或創建一個新的對象:

選項A:

// score is higher move records down 
for (jx = mNumRecords - 1; jx >ix ; jx--) 
{ 
    sTable[jx].time = sTable[jx -1].time; 
    sTable[jx].score = sTable[jx -1].score; 
} 
//now add new score 
sTable[ix].score = score; // all good until here 
sTable[ix].time = time; 

選項B:

for (jx = mNumRecords - 1; jx >ix ; jx--) 
{ 
    sTable[jx] = sTable[jx -1]; 
} 
sTable[ix] = new Result(score, time, ""); // Or however you construct the object 
+0

選項A解決了我的問題。謝謝Binyamin。有一點明顯曾經指出(他說拍頭!!) – Squiggles 2012-01-15 05:57:53