Java 从数组列表向int添加值
我正在做一个个人项目来创建一个游戏。 我似乎遇到的麻烦是让变量runs增加值。 我已将我的值设置为零。我尝试使用runs++,虽然它只增加了一个。 我想做的是根据if语句的结果增加1或6。 如果有人能指出解决问题的正确方向,那就太好了Java 从数组列表向int添加值,java,if-statement,arraylist,count,integer,Java,If Statement,Arraylist,Count,Integer,我正在做一个个人项目来创建一个游戏。 我似乎遇到的麻烦是让变量runs增加值。 我已将我的值设置为零。我尝试使用runs++,虽然它只增加了一个。 我想做的是根据if语句的结果增加1或6。 如果有人能指出解决问题的正确方向,那就太好了 public class BatsmanDice { public static void rollBatsmanDice() { // Roll player dice decides how many runs are scored when the
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);
ArrayList batsmanDiceOptions=new ArrayList();
//你的代码
runs+=batsmanDiceOptions.get(0);
按某个随机值递增运行次数get(0)
返回一个随机值,因为您已经洗牌了ArrayList
话虽如此。。。若要模拟掷骰子,为什么不按1到6的随机数递增?我建议使用ArrayList从帽子中拾取有限的项目,因为这样.remove()就很有用了。对于掷骰子,我可能只使用
Random
您使用的是ArrayList,这是非常糟糕的做法,应该避免。但是一个普遍的问题是:如果你只想创建一个介于1-6之间的随机数,为什么不使用标准的JavaJava.util.random
类及其nextInt
方法(如random.nextInt(6)+1
)?当我研究如何利用骰子选项时,我最初使用的是random.nextInt。我遇到的麻烦是,我的骰子包括1到6个单词。是否有更好的选项是将6个int值和一个字符串随机化的最佳实践?它真的需要是一个字符串吗?您不能从0-6(而不是1-6)创建随机数,并且在滚动0时,您可以执行与当前选择字符串时相同的逻辑吗?谢谢您的回复!我会试试那个选项的。我会试试那个选项的。谢谢。游戏的骰子选项包括1-6和字符串“Owzthat”。也许我可以设置随机整数。然后将字符串变量作为随机布尔值运行。@CodyJohannessen我明白了-那么ArrayList对您不起作用。你可以用一个骰子1-7吗?如果你选择了一个7,处理这个问题并把它改成“Owzthat”?谢谢你的回复,我会尝试提供的选项!