【发布时间】: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