String part1=parts[0];
String part2=parts[1];
String part3=parts[2];
System.out.print(part3);
sasdasd ASD ASD ASD ASD ASD ASD ASD ASD asdasdasd ASD ASD ASD asdasdasdasd ASD作爲ASD asdas DASD作爲DASD asdasdasdasdasdasd字符串錯誤
String part1=parts[0];
String part2=parts[1];
String part3=parts[2];
System.out.print(part3);
sasdasd ASD ASD ASD ASD ASD ASD ASD ASD asdasdasd ASD ASD ASD asdasdasdasd ASD作爲ASD asdas DASD作爲DASD asdasdasdasdasdasd字符串錯誤
if (string.contains("-")) {
parts= string.split("d|\\-");
String part1=parts[0];
String part2=parts[1];
String part3=parts[2];
}else{
parts= string.split("d");
String part1=parts[0];
String part2=parts[1];
}
for (int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
的正則表達式與捕獲組可用於解析String
。只要檢查該組的String
是否爲null
,就可以測試各個組的存在。例如:
Pattern pattern = Pattern.compile("(\\d+)d(\\d+)([+-]\\d+)?");
for (String s : new String[] {
"2d6",
"3d8",
"4d6-2",
"4d6+9",
"2d6-10",
"2d6-1x9"
}) {
System.out.println(s);
Matcher m = pattern.matcher(s);
if (m.matches()) {
int i1 = Integer.parseInt(m.group(1));
int i2 = Integer.parseInt(m.group(2));
String summand = m.group(3);
int i3 = summand == null ? 0 : Integer.parseInt(summand);
System.out.println(MessageFormat.format("{0}D{1}+({2})", i1, i2, i3));
} else {
System.out.println("no match");
}
}
輸出:
2d6
2D6+(0)
3d8
3D8+(0)
4d6-2
4D6+(-2)
4d6+9
4D6+(9)
2d6-10
2D6+(-10)
2d6-1x9
no match
我覺得很難相信,你在'的System.out.println得到一個錯誤(3); '... – alfasin
在訪問之前檢查數組的長度 – Kelvin