2016-09-17 203 views
0
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字符串錯誤

+0

我覺得很難相信,你在'的System.out.println得到一個錯誤(3); '... – alfasin

+0

在訪問之前檢查數組的長度 – Kelvin

回答

2

可以檢查數組的長度:

if (parts.length > 1) { 
    ... // what to do if the string contains the delimiter 
} 
else { 
    ... // what to do if the string does not contain the delimiter 
} 
+0

謝謝先生:)它做到了。 – ETC

+0

你可以給我任何想法如何驗證Jtextfield的格式相同 截至2d6,3d8或6d-10 (Numbers d Numbers)/(Numbers d Numbers - Numbers) – ETC

0
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]); 
       } 
0

的正則表達式與捕獲組可用於解析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