3 回答

TA貢獻1833條經(jīng)驗 獲得超4個贊
您需要檢查 dateofbirth 格式是否正確,并通過檢查數(shù)組長度來防止異常。
String [] dob= dateofbirth.split("/");
if(dob != null && dob.length >=3){
System.out.println(""+dob[0]);
System.out.println(""+dob[1]);
System.out.println(""+dob[2]);
}

TA貢獻1808條經(jīng)驗 獲得超4個贊
似乎數(shù)組 dob 只有一個元素,其中沒有索引 1。這就是為什么您會看到java.lang.ArrayIndexOutOfBoundsException: 1 索引從 0 開始。
使用循環(huán)來導航數(shù)組,以便您可以根據(jù)數(shù)組大小動態(tài)處理用例。舉個例子,見下文。
例子
String input = "abc/def/ghi/jkl";
String[] matrix = input.split("/");
/* Print each letter of the string array in a separate line. */
for(int i = 0; i < matrix.length; ++i) {
System.out.println(matrix[i]);
}
這將給出如下輸出,
abc
def
ghi
jkl
這樣可以避免遇到java.lang.ArrayIndexOutOfBoundsException:

TA貢獻1850條經(jīng)驗 獲得超11個贊
您應該使用數(shù)組索引越界異常嘗試捕獲。
try {
String [] dob= dateofbirth.split("/");
System.out.println(""+dob[0]);
System.out.println(""+dob[1]);
System.out.println(""+dob[2])
catch(ArrayIndexOutOfBoundsException exception) {
handleTheExceptionSomehow(exception);
}
添加回答
舉報