【问题标题】:How to I make this code to print the highest value(s) in the array? [duplicate]如何使此代码打印数组中的最大值? [复制]
【发布时间】:2018-11-19 16:26:44
【问题描述】:

如何让这段代码打印数组中的最大值?

示例 (view detailled screenshot):

  • 玩家 1 得分 = 1
  • 玩家 2 得分 = 2
  • 玩家 3 得分 = 1

    玩家 2 是赢家。

  • 玩家 1 得分 = 1

  • 玩家 2 得分 = 3
  • 玩家 3 得分 = 3

    玩家 2 是赢家。
    玩家 3 是赢家。

  • 玩家 1 得分 = 1

  • 玩家 2 得分 = 1
  • 玩家 3 得分 = 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
}

【问题讨论】:

  • 是什么阻止您在网上搜索以找到找到数组最大值的解决方案?
  • 这是重复的,因为没有人帮助我¿?
  • 没有什么能阻止我,我需要帮助才能打印数组的多个获胜者,而不仅仅是一个
  • 是的,我写了那个评论聪明的家伙。这是我唯一需要的 cse 课程,我没有教科书,所以我在网上寻求帮助。 chegg 上的某个人帮助了我足够多的东西,无论如何我都可以弄清楚其余部分,代码在这篇文章的唯一答案下方作为评论,以防其他人需要帮助。不用感谢这个人^

标签: java arrays sorting max


【解决方案1】:

迭代playerScore,将其值与上一次迭代之前的最大值进行比较,如果迭代为零,则为 0。如果较大,则最大值为迭代值。

int maximumValue = 0;
for(int i = 0; i < playerScore.length; i++) {
    if(playerScore[i] > maximumValue) {
        maximumValue = playerScore[i];
    }
}

要检查具有最大值的播放器,您可以使用与以前相同的代码 sn-p:

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));

【讨论】:

  • int最高分数=-1; for (int i = 0; i highestScore) {highestScore = Cards.pointValue(hand); } } if (playerScore[i] == highestScore) { System.out.println("玩家 " + (i + 1) + " 是赢家"); } }
  • 循环遍历数组两次^
猜你喜欢
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
  • 2020-03-10
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 2017-12-08
相关资源
最近更新 更多