2015-03-08 44 views
0

我試圖循環訪問我創建的數組的變量,以將「優勝者」拉到新數組中。 我可以把分數拿過來,但後來失去了它在陣列中的位置。拉一個變量及其在陣列中的位置

基本上,我希望它這樣做:

players = [23,41,15,65,18] 
Player 4 has won(with a score of 65) 
+0

我回答了您的問題嗎? – lacraig2 2015-03-08 21:10:41

回答

5

要找到一個數組的最大元素。 (以及最高得分)

int max = 0; 
int player = 0; 
for (int i=0; i<players.length; i++){ 
    if (players[i] > max){ 
     player = i+1; 
     max = players[i] 
    } 
} 
System.out.println("Player "+player+" has won(with a score of "+max+")"); 

我希望這會有所幫助。

編輯:正如有人指出的球員(如果計算第一個爲1)將是我+ 1。謝謝。

+0

而不是'player = i + 1;'i == 0的玩家是玩家1; i == 3的玩家是玩家4;你明白了。 – J0e3gan 2015-03-08 21:11:29

+0

幹得好。補充說。謝謝。 – lacraig2 2015-03-08 21:13:00

相關問題