【发布时间】:2016-09-26 22:02:16
【问题描述】:
我整天都在做这件事,我一辈子都无法弄清楚我做错了什么。该代码使我的 Android 模拟器崩溃。我正在尝试做的是编写一个掷骰子程序,我让它与作为单个实体滚动的骰子一起工作,但我正在尝试处理像 3d6 或 5d4 这样的掷骰子。对 singleRoll 的调用一次滚动一个骰子,我试图将更长的方程式分解为更简单的位...“3d4+5-13d6+7d8+9”
bbs.randInt 返回 [0,diceSize)。
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
// TODO: Replace 5d4 with d4+d4+d4+d4+d4
for (String partOfRoll : parts) { //roll each dice specified
if (partOfRoll.matches("\\d+d\\d+")) {
String[] splitString = (partOfRoll.split("d"));
int times = Integer.getInteger(splitString[0]);
int die = Integer.getInteger(splitString[1]);
int i;
for (i = 0; i < times; i++) {
String rollStr = "d" + die;
total += singleRoll(rollStr);
}
}
else {
total += singleRoll(partOfRoll);
}
}
return total;
}
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = bbs.randInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}
【问题讨论】:
-
您遇到错误了吗?如果是这样,请发布堆栈跟踪。
-
singleRoll(String)方法在哪里?您也可以发布该代码吗? -
public int singleRoll(String roll) { int di = roll.indexOf('d'); if (di == -1) //case where has no 'd' return Integer.parseInt(roll); int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd' int result = bbs.randInt(diceSize) + 1; //roll the dice if (roll.startsWith("-")) //negate if nessasary result = -result; return result; } -
对不起,我是新人。我不知道如何在评论中发布代码。
-
使用该代码编辑您的主帖。
标签: java calculator dice