我正在编写一个Monopoly的模拟程序,我想知道是否有一种方法可以解决变量,如果它超过一个数而不是另一个变量?
while (i<=200){
while(Player1.space<41 || Player2.space<41){
roll();
Player1.space=Player1.space+roll();
System.out.println("Player1 "+Player1.space);
i++;
roll();
Player2.space=Player2.space+roll();
System.out.println("Player2 "+Player2.space);
i++;
}
//So here I want to reset the variable that reached 41 back to one.
}
}
答案 0 :(得分:3)
我会这样做:
int moveTo = Player1.space + roll();
Player1.space = moveTo > 40 ? moveTo - 40 : moveTo;
这假设您的space
编号从1开始(如果您说40
是有效空格,并且您的评论中您希望&#34;重置变量)达到41回到了一个&#34;)。
然后你不再需要内部while循环,所以你只需要
while (i <= 200) {
int moveTo = Player1.space + roll();
Player1.space = moveTo > 40 ? moveTo - 40 : moveTo;
...
使用模数运算符(除以40
并使用余数作为输出)它会变短:
Player1.space = (Player1.space + roll()) % 40;
如果您的空间编号从0开始,这种方法非常有效,但如果从1开始,则可以进行调整,如下所示:
Player1.space = 1 + ((Player1.space + roll() - 1) % 40);
您可以通过以下方式查看两者之间的区别:
public static void main(String[] args) {
for (int moveTo = 0; moveTo < 50; moveTo++) {
int space = moveTo > 40 ? moveTo - 40 : moveTo;
System.out.println("" + moveTo + " " + space);
}
for (int moveTo = 0; moveTo < 50; moveTo++) {
int space = moveTo % 40;
System.out.println("" + moveTo + " " + space);
}
}