我正在开展一个创建游戏的个人项目。 我似乎遇到的麻烦是让我的变量“runs”增加值。 我已将我的值设置为零。我尝试使用运行++,尽管它只增加一。 我想要做的是根据 if 语句的结果增加 1 或 6。 如果有人能够指出如何解决的正确方向,那就太好了!
public class BatsmanDice {
public static void rollBatsmanDice() {
// Roll player dice decides how many runs are scored when the player rolls.
// We have options from 1 to 6 and Owzthat.
// When Owzthat is triggered we return to the main method and run rollUmpireDice();
// Using an Array list to have all options available.
ArrayList batsmanDiceOptions = new ArrayList();
batsmanDiceOptions.add(1);
batsmanDiceOptions.add(2);
batsmanDiceOptions.add(3);
batsmanDiceOptions.add(4);
batsmanDiceOptions.add(5);
batsmanDiceOptions.add(6);
batsmanDiceOptions.add("Owzthat");
int runs = 0;
System.out.println("Total runs " + runs);
// We take our Array list from above and shuffle it using the Collections import tool.
Collections.shuffle(batsmanDiceOptions);
// We then take the shuffled array list and print 1 options to screen showing the dice rolled
// Commented out print line statement to return a random shuffled array option
//System.out.println(batsmanDiceOptions.get(1));
if (batsmanDiceOptions.contains(1)) {
System.out.println(" Scored 1 Run " + batsmanDiceOptions.get(1));
}
}
}
最佳答案
如果这是你所问的,我不肯定。但如果您想“滚动”并增加运行次数,只需执行以下操作:
ArrayList<Integer> batsmanDiceOptions = new ArrayList<Integer>();
// your code
runs += batsmanDiceOptions.get(0);
按某个随机值递增运行。 get(0)
返回一个随机值,因为您已经对 ArrayList 进行了洗牌。
话虽这么说......为了模拟掷骰子,为什么不只是增加一个从 1 到 6 的随机数?我建议使用 ArrayList 来处理诸如从帽子中挑选有限项之类的事情,因为这样 .remove() 就变得有用了。对于掷骰子,我可能只会使用Random
。
关于java - 将数组列表中的值添加到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775082/