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

标签 java arrays sorting max

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

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

相关文章:

java - Gson 中的 @Until 注释未按预期工作

java - 动态获取 Apache Tomcat 服务器路径和端口

arrays - Redux reducer ,检查状态数组中是否存在值并更新状态

Javascript数组按给定顺序排序

c++ - 如何在保持主要排序的同时执行次要排序

java - 在 RH 计算机上禁用系统范围内的 Java 大页面

java - ActivityCompat.requestPermissions 不显示提示

iphone - 将UIView中的UIImageView对象添加到NSMutableArray中

java - 扫描文件并将其分配给对象数组时获取 "Mismatch error"

python - 根据值列表在 python 中重新排序字典