如何在Java中分别比较两个int数组的元素,并确定哪个元素更大?

huangapple go评论56阅读模式
英文:

How do you compare two int arrays elements separately in Java and see which is the greater element?

问题

public class Exercise1 {

    public static void main(String[] args) {

        int[] playerOne = new int[7];
        int[] playerTwo = new int[7];

        playerOne[0] = 10;
        playerOne[1] = 6;
        playerOne[2] = 8;
        playerOne[3] = 9;
        playerOne[4] = 7;
        playerOne[5] = 12;
        playerOne[6] = 7;

        playerTwo[0] = 7;
        playerTwo[1] = 6;
        playerTwo[2] = 9;
        playerTwo[3] = 5;
        playerTwo[4] = 2;
        playerTwo[5] = 8;
        playerTwo[6] = 11;

        for (int i = 0; i < playerOne.length; i++) {
            if (playerOne[i] > playerTwo[i]) {
                System.out.println("Player One wins round " + (i + 1));
            } else if (playerOne[i] < playerTwo[i]) {
                System.out.println("Player Two wins round " + (i + 1));
            } else {
                System.out.println("Round " + (i + 1) + " is a draw.");
            }
        }
    }
}
英文:

So I have to make a game that compares two int arrays elements separately and see if one is greater than the other or if they equal and print a message declaring which player won or if it was a draw. Both players are given 7 cards so they have to be compared 7 times each in a different round.
I'm stuck when it comes to comparing each number I cant get seem to get it to work and I don't really know how to make it so every iteration declares a new round would that have to be done separately 7 times?
This is what I currently have after many attempts.
Any help would be greatly appreciated!

public class Exercise1 {


public static void main(String[] args) {
    
    int[] playerOne = new int[6];
    int[] playerTwo = new int [6];
    
    
    
    playerOne[0] = 10;
    playerOne[1] = 6;
    playerOne[2] = 8;
    playerOne[3] = 9;
    playerOne[4] = 7;
    playerOne[5] = 12;
    playerOne[6] = 7;
    
    playerTwo[0] = 7;
    playerTwo[1] = 6;
    playerTwo[2] = 9;
    playerTwo[3] = 5;
    playerTwo[4] = 2;
    playerTwo[5] = 8;
    playerTwo[6] = 11;
            
    
     for (int i = 0; i &lt;= playerOne.length - 1; i++) {
         if (playerOne[i] &lt; playerTwo) {
             
         }

答案1

得分: 3

看起来你想要将相同索引处的元素进行比较,所以你的代码几乎是正确的:

  • 比较 playerOne[i]playerTwo[i],然后执行适当的操作(例如计算得分)
  • 请记住,最大的索引由较短的数组定义,所以要么确保它们的长度相同,要么使用 i < Math.min(playerOne.length, playerTwo.length)

然而,重新思考你的方法可能会更好(尽管这可能是以后的练习):不要维护两个单独的“回合”得分数组,而是尝试将其合并为一个数组,引入一个 RoundResults 类(或类似的类),最好使用一个列表(具有动态长度)。

示例(简化):

class RoundResult {
   private int playerOneScore;
   private int playerTwoScore;

   // 构造函数,getter 和 setter
}

List<RoundResult> rounds = new ArrayList<>();
rounds.add(new RoundResult(10, 7));
rounds.add(new RoundResult(6, 6));
...

for (RoundResult round : rounds) {
   if (round.getPlayerOneScore() < round.getPlayerTwoScore()) {
      // 玩家 2 赢得了这一回合
   } else if (round.getPlayerOneScore() > round.getPlayerTwoScore()) {
      // 玩家 1 赢得了这一回合
   } else {
      // 平局
   } 
}

这样做有几个优点:

  • 使用列表不需要在编译时知道回合的数量(例如,当你想要继续直到一个玩家比另一个玩家多赢了至少 x 个回合时)
  • 只有一个列表,所以不必确保两个数组或列表具有相同的大小和顺序
  • 甚至可以在 RoundResult 中添加像 boolean isDraw() { ... } 这样的方法。
英文:

It looks like you want to compare the elements at the same indices to each other so your code is almost good:

  • compare playerOne[i] to playerTwo[i] and do whatever is appropriate (e.g. count the score)
  • keep in mind that the maximum index is defined by the shorter array so either make sure they both have the same length or use i &lt; Math.min(playerOne.length, playerTwo.length).

However, it might be better to rethink your approach (which might be a later exercise though): instead of maintaining 2 separate arrays of "round" scores try to put it into one by introducing a RoundResults class (or similar) and ideally using a list (which has dynamic length).

Example (simplified):

class RoundResult {
   private int playerOneScore;
   private int playerTwoScore;

   //constructor, getters and setters
}

List&lt;RoundResult&gt; rounds = new ArrayList&lt;&gt;();
rounds.add(new RoundResult(10, 7));
rounds.add(new RoundResult(6, 6));
...


 for(RoundResult round : rounds) {
   if( round.getPlayerOneScore() &lt; round.getPlayerTwoScore() ) {
      //player 2 won that round
   } else if( round.getPlayerOneScore() &gt; round.getPlayerTwoScore() ) {
      //player 1 won that round
   } else {
      //it was a draw
   } 
 }

Doing it like this has several advantages:

  • using a list doesn't require to know the number of rounds at compile time (e.g. when you'd want to go on until one player has won at least 2 rounds more than the other with a minimum of x)
  • you have only one list so you don't have to make sure 2 arrays or lists have the same size and order
  • you could even add methods to RoundResult like boolean isDraw() { ... }

答案2

得分: 2

你需要两个变量来保存每个玩家的分数,在每一轮中增加持有更大卡牌的玩家的分数,在结束时找到最大的分数。

int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};

int scorePlayerOne = 0, scorePlayerTwo = 0;

for (int i = 0; i <= playerOne.length - 1; i++) {
    if (playerOne[i] < playerTwo[i]) {
        scorePlayerTwo++;
    } else if (playerTwo[i] < playerOne[i]) {
        scorePlayerOne++;
    }
}

if (scorePlayerOne < scorePlayerTwo) {
    System.out.println("Player Two wins");
} else if (scorePlayerTwo < scorePlayerOne) {
    System.out.println("Player One wins");
} else {
    System.out.println("Draw");
}
英文:

You need 2 variables that holds each ones score, increment the one that has the bigger card for each round, at the end find the biggest score

int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};

int scorePlayerOne = 0, scorePlayerTwo = 0;

for (int i = 0; i &lt;= playerOne.length - 1; i++) {
    if (playerOne[i] &lt; playerTwo[i]) {
        scorePlayerTwo++;
    } else if (playerTwo[i] &lt; playerOne[i]) {
        scorePlayerOne++;
    }
}

if (scorePlayerOne &lt; scorePlayerTwo) {
    System.out.println(&quot;Player Two wins&quot;);
} else if (scorePlayerTwo &lt; scorePlayerOne) {
    System.out.println(&quot;Player One wins&quot;);
} else {
    System.out.println(&quot;Draw&quot;);
}

答案3

得分: 0

int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};

int position = 0;

for(int i = 0; i< playerOne.length; i++)
position += Integer.compare(playerOne[i], playerTwo[i]);

String result = (position < 0)? "Player One": (position > 0)? "Player Two" : "Equal";
System.out.println(result);

英文:
int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};

int position = 0;

for(int i = 0; i&lt; playerOne.length; i++)
    position += Integer.compare(playerOne[i], playerTwo[i]);

String result = (position &lt; 0)? &quot;Player One&quot;: (position &gt; 0)? &quot;Player Two&quot; : &quot;Equal&quot;;
System.out.println(result);

The For loop iterates through one element per array per iteration, and it increments or decrements the 'position' variable by comparing the elements in an iteration.

If Player One is greater then the final value of 'position' would be negative as there were more decrements and vice versa.

huangapple
  • 本文由 发表于 2020年9月5日 01:53:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63745936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定