如何制作此代码以打印数组中的最高值?
示例(view detailled screenshot):
玩家3得分= 1
玩家2是赢家。
玩家1得分= 1
玩家3得分= 3
玩家2是赢家。
玩家3是赢家。
玩家1得分= 1
玩家1是赢家。
玩家2是赢家。
玩家3是获胜者。`
到目前为止,这是我尝试编写的代码:
/**
* [algorithm description here]
* @param players
* @param cards
*/
public static void playGame(int players, int cards) {
if (players * cards > 52) {
System.out.println("Not enough cards for that many players.");
return;
}
boolean[] deck = new boolean[52];
int[] playerScore = new int[players];
for (int i = 0; i < players; i++) {
System.out.println("Player " + (i + 1));
int[] hand = Cards.dealHandFromDeck(cards, deck);
Cards.printHand(hand);
System.out.println("Score = " + Cards.pointValue(hand));
System.out.println();
playerScore[i] = Cards.pointValue(hand);
}
//go through playerScore array twice, first to find the highest score, then who has that score
}
答案 0 :(得分:1)
迭代playerScore
,将其值与最大值进行比较,直到前一次迭代为止;如果迭代为零,则返回0。如果更大,则最大值为迭代值。
int maximumValue = 0;
for(int i = 0; i < playerScore.length; i++) {
if(playerScore[i] > maximumValue) {
maximumValue = playerScore[i];
}
}
要检查播放器的最大值,可以使用与以前相同的代码段:
int maximumValue = 0;
long player = -1;
for(int i = 0; i < playerScore.length; i++) {
if(playerScore[i] > maximumValue) {
maximumValue = playerScore[i];
player = i;
}
}
if(player > -1) System.out.println("Player with highest score: " + (player + 1));