gpt4 book ai didi

java - 如何使此代码打印数组中的最高值?

转载 作者:行者123 更新时间:2023-12-02 10:34:42 24 4
gpt4 key购买 nike

如何使此代码打印数组中的最高值?

示例(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com