首页 > 解决方案 > 从数组列表向 int 添加值

问题描述

我正在做一个个人项目来创建一个游戏。我似乎遇到的麻烦是让我的变量称为运行以增加价值。我已将我的值设置为零。我尝试使用 runs++,尽管它只增加了 1。我要做的是根据 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));
  }

 }

}

标签: javaif-statementarraylistcountinteger

解决方案


如果这是您要问的,我不肯定。但是,如果您尝试“滚动”并增加运行,只需执行以下操作:

ArrayList<Integer> batsmanDiceOptions = new ArrayList<Integer>();

// your code

runs += batsmanDiceOptions.get(0);

通过一些随机值增加运行。get(0)返回一个随机值,因为您已经对 ArrayList 进行了洗牌。

话虽这么说……为了模拟掷骰子,为什么不增加一个从 1 到 6 的随机数呢?我建议将 ArrayList 用于从帽子中挑选有限项之类的事情,因为这样 .remove() 就变得有用了。对于掷骰子,我可能只会使用Random.


推荐阅读