如果我有這樣的如何根據其中一個對象屬性的值從數組中選擇一個隨機元素?
resources[0] = new Resource("Brick", 0x990000, 3);
resources[1] = new Resource("Wool", 0xFFFFFF, 4);
resources[2] = new Resource("Lumber", 0x006600, 4);
resources[3] = new Resource("Stone", 0x999999, 3);
resources[4] = new Resource("Wheat", 0xFFFF33, 4);
resources[5] = new Resource("Wasteland", 0xcc9966, 1);
數組我如何選擇具有大於0的可用性的隨機資源?這是我當前的嘗試:
int[] diceSpaces = {2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12};
diceSpaces = shuffleArray(diceSpaces);
for(int i = 0; i < diceSpaces.length; i++){
Resource currentResource = null;
for(int r = 0; r < resources.length; r++){
int tryResource = new Random().nextInt(resources.length);
if(diceSpaces[i] != 7){
if(resources[tryResource].available > 0){
currentResource = resources[tryResource];
break;
}
} else {
currentResource = resources[5];
break;
}
}
currentResource.available--;
}
你的代碼很混亂......那裏面有什麼變數?你的意思是r。 – vilpe89
這段代碼還有兩個循環,因爲我沒有認爲它們是相關的,所以我沒有包含這些代碼。道歉。 – ShoeLace1291
@ ShoeLace1291什麼不工作? – brso05