简体   繁体   English

JAVA:如何添加两个声明相同名称但值不同的处理值

[英]JAVA: How do I add two processed values with same name declared but different values

I am looking for a way to sum up the two "final scores" of player 1 into a total score of player1 that I can compare with another player's total score later.我正在寻找一种方法将玩家 1 的两个“最终得分”相加为玩家 1 的总得分,以便稍后与其他玩家的总得分进行比较。

int player11, player12, player21, player22;
int score1;
int score2 = 0;

Random random = new Random();
int i=0;
do {
    do {
        System.out.println("Player 1 rolls the dice");
        player11 = random.nextInt(6) + 1;
        player12 = random.nextInt(6) + 1;
        score1 = player11 + player12;
        System.out.println(player11 + "\t" + player12 + "\t" + score1);
        if (player11 == 1 && player12 == 1) {
            score1 = score1 * 2;
            
        } else if ((player11 % 2 != 0 && player12 % 2 != 0) && (player11 != 1 && player12 != 1)) {
            score1 -= 5;
        } else if (player11 == 6 && player12 == 6) {
            System.out.println("Player 1 rerolls the dice");
            score1 = 0;
        }
    } while (player11 == 6 && player12 == 6);
    
    System.out.println("Final Score: " + score1);
    i++;
} while (i<2);

So far what I have understood is you want to add the score after each iteration right ?到目前为止,我所了解的是您想在每次迭代后添加分数,对吗? In that case you can just use a temp to store the score for the calculation and then add it after the inner do-while loop is complete.在这种情况下,您可以使用 temp 来存储计算的分数,然后在内部 do-while 循环完成后添加它。 Like following:像下面这样:

do {
    int temp = 0; //New variable to temporarily save scores
      do {
        System.out.println("Player 1 rolls the dice");
        player11 = random.nextInt(6) + 1;
        player12 = random.nextInt(6) + 1;
        temp = player11 + player12; //instead of score we're saving it in temp
        /* your code continued..... 
        remember to swap score1 with temp at every place
        .....
        .....
        */
        }
    } while (player11 == 6 && player12 == 6);
    score1 = score1 + temp; // Finally we add it in the score1 variable
    System.out.println("Final Score: " + score1);
    i++;
} while (i<2);

I hope this resolves the trivial issue.我希望这能解决这个微不足道的问题。 Also I think you didn't initialize the score1 variable which might cause issues.另外我认为您没有初始化可能导致问题的 score1 变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM