如何使此代码打印数组中的最高值?
示例(view detailled screenshot):
- 玩家 1 得分 = 1
- 玩家 2 得分 = 2
玩家 3 得分 = 1
Player 2 is the winner.
玩家 1 得分 = 1
- 玩家 2 得分 = 3
玩家 3 得分 = 3
Player 2 is the winner.
Player 3 is the winner.玩家 1 得分 = 1
- 玩家 2 得分 = 1
- 玩家 3 得分 = 1
Player 1 is the winner.
Player 2 is the winner.
Player 3 is the winner.`
到目前为止,这是我的代码尝试:
/**
* [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
}
最佳答案
迭代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));
关于java - 如何使此代码打印数组中的最高值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378890/