java - 从数组列表向 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));
}
}
}
解决方案
如果这是您要问的,我不肯定。但是,如果您尝试“滚动”并增加运行,只需执行以下操作:
ArrayList<Integer> batsmanDiceOptions = new ArrayList<Integer>();
// your code
runs += batsmanDiceOptions.get(0);
通过一些随机值增加运行。get(0)
返回一个随机值,因为您已经对 ArrayList 进行了洗牌。
话虽这么说……为了模拟掷骰子,为什么不增加一个从 1 到 6 的随机数呢?我建议将 ArrayList 用于从帽子中挑选有限项之类的事情,因为这样 .remove() 就变得有用了。对于掷骰子,我可能只会使用Random
.
推荐阅读
- odoo - OpenERP - ValueError:系统中当前没有定义这样的外部ID:project.group_project_manager
- javascript - JavaScript 为数据分配数字
- c# - 成功写入事件日志(并收到一条我不明白的消息)
- c - 汇编中的内存分配和寻址
- java - 球体体积
- django - Django UpdateView:ValueError:int()的无效文字,基数为10:用户名
- html - 如何在浏览器中打开保存在 wwwroot 下的文件夹中的文件?
- image-processing - 为什么这个图像对我来说是错误的?
- powershell - 复制前 PowerShell 复制项检查目标是否具有相同的文件名
- c# - 如何在 C# 中连接多台服务器和数据库