我有一個二維整數數組,代表我用來追蹤遊戲中物體位置的地圖。它被一個程序系統修改,它將改變那裏的數字來放置不同的對象。我會設置每個Int的值作爲0,1或2看起來是這樣的:由於程序上的步驟很大程度上依賴於隨機有一個更清晰的方法來留在數組的邊界內嗎?
00010
00100
02120
21200
12000
,我想提出幾個檢查到位,如果陣列位置我試圖寫入數組的範圍之外,它會回落到地圖的邊緣而不是導致錯誤。例如我嘗試在[0,10]中輸入一個條目,它將默認爲[0,4]。 是的,我知道我應該小心確保我永遠不會試圖在數組邊界之外進行寫入,但給出了其他每次都不會發生的元素。理智檢查似乎是謹慎的。
我提出的解決方案的工作,但它似乎過分冗長和冗長。有沒有我不知道的更清潔的解決方案?
下面的代碼示例:
//Example of something randomly being written to the array
random r = new Random();
int xMax = field.GetLength(0);
field[mid(r.next(0,5), 0, xMax), 0] = 1;
//Method for sanity bounds.
private static int mid(int target, int min, int max)
{
//Target is the value we want
//Min is the smallest possible value
//Max is the largest possible value.
if (target == min)
{
return min;
}
if (target == max)
{
return max;
}
if (target < max && target > min)
{
return target;
}
else if (target > max && target > min)
{
return max;
}
else if (target < min && target < max)
{
return min;
}
return min; //This shouldn't ever get trigger. In here so compiler won't complain.
}
我沒有回答你的問題,但也許你在你的方法最後一行 - '回報min' - 如果它應該拋出一個異常未定義/意外的行爲。 – 2014-09-12 16:14:51
如果你正在訪問一個無效的索引,你應該*想讓你的程序崩潰,這樣你就會意識到你有一個bug並且可以修復它,而不是簡單地訪問錯誤的數組值並且隱藏問題,將難以發現和診斷。 – Servy 2014-09-12 16:17:02
@DanPantry他不需要那樣做。在這種情況下,他可以刪除整個事物,只需讓數組索引器拋出一個超出綁定異常的索引即可。 – Servy 2014-09-12 16:17:30