我一直在這一整天,我不能爲我的生活弄清楚我做錯了什麼。該代碼崩潰我的Android模擬器。我試圖做的是編寫一個骰子滾動程序,我把它作爲單個實體滾動,但我試圖處理像3d6或5d4的骰子滾動。對SingleRoll的調用一次擲出一個模子,我試圖將一個更長的方程分解成更簡單的位......「3d4 + 5-13d6 + 7d8 + 9」在Java骰子滾動程序中的正則表達式幫助
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;
}
您是否收到錯誤?如果是這樣,請發佈堆棧跟蹤。 – shmosel
'singleRoll(String)'方法在哪裏?你可以發佈該代碼嗎? – Alexander
'public int singleRoll(String roll){ int di = roll.indexOf('d'); if(di == -1)// case where no'd' return Integer.parseInt(roll); int diceSize = Integer.parseInt(roll。子串(di + 1)); // d'後的字符串值 int result = bbs.randInt(diceSize)+ 1; //滾動骰子 if(roll.startsWith(「 - 」))//否定如果nessasary result = -result; 返回結果; }' –