【问题标题】:Adding values to int from Array List从数组列表向 int 添加值
【发布时间】:2020-01-16 17:38:52
【问题描述】:

我正在开发一个个人项目来创建一个游戏。 我似乎遇到的麻烦是让我的变量称为运行以增加价值。 我已将我的值设置为零。我尝试使用 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));
  }

 }

}

【问题讨论】:

  • 您将 ArrayList 用作raw type,这是非常糟糕的做法,应该避免。但是一个普遍的问题:如果你只是想创建一个 1-6 之间的随机数,为什么不使用标准的 Java java.util.Random 类及其nextInt 方法(如random.nextInt(6) + 1)?
  • 当我研究使用骰子选项的方法时,我最初使用的是 random.nextInt。我遇到的麻烦是我的骰子包括1到6以及一个单词。是否有更好的选择是随机化 6 个 int 值和一个字符串的最佳实践?
  • 真的需要是字符串吗?难道你不能只从 0-6(而不是 1-6)创建随机数,当滚动 0 时,你会执行与当前选择字符串时相同的逻辑吗?
  • 感谢您的回复!我会试试那个选项。

标签: java if-statement arraylist count integer


【解决方案1】:

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

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

// your code

runs += batsmanDiceOptions.get(0);

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

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

【讨论】:

  • 我会试试这个选项,谢谢。游戏的骰子选项包括 1 - 6 和字符串“Owzthat”。也许我可以设置随机整数。然后将字符串变量作为随机布尔值运行。
  • @CodyJohannessen 我明白了 - 那么 ArrayList 将不适合你。您是否可以只使用 1-7 骰子,如果您选择 7,请处理该情况并将其更改为“Owzthat”?
  • 感谢您的回复,我会尝试提供的选项!
猜你喜欢
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2013-10-28
  • 2021-08-29
相关资源
最近更新 更多