[英]JAVA: How do I add two processed values with same name declared but different values
我正在尋找一種方法將玩家 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);
到目前為止,我所了解的是您想在每次迭代后添加分數,對嗎? 在這種情況下,您可以使用 temp 來存儲計算的分數,然后在內部 do-while 循環完成后添加它。 像下面這樣:
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);
我希望這能解決這個微不足道的問題。 另外我認為您沒有初始化可能導致問題的 score1 變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.