4 回答

TA貢獻1784條經驗 獲得超9個贊
string.split("\n")返回一個String數組。
string.split("\n")[1]假定返回值是一個至少有兩個元素的數組。
ArrayIndexOutOfBoundsException表示該數組的元素少于兩個。
如果要防止出現該異常,則需要檢查數組的長度。就像是...
String[] parts = string.split("\n");
if (parts.length > 1) {
System.out.println(parts[1]);
}
else {
System.out.println("Less than 2 elements.");
}

TA貢獻1776條經驗 獲得超12個贊
索引從 0 開始,因此通過使用 1 進行索引,您試圖獲取數組的第二個元素,在您的情況下,它可能是文本的第二行。您遇到這樣的錯誤是因為您的字符串中可能沒有換行符,為避免此類異常,您可以使用 try catch 塊(在您的情況下我不喜歡這種方法)或者只檢查是否有換行符你的字符串,你可以這樣做:
if(yourString.contains("\n")){
//split your string and do the work
}
甚至通過檢查分割部分的長度:
String[] parts = yourString.split("\n");
if(parts.length>=2){
//do the work
}
如果你想使用 try-catch 塊:
try {
String thisPart = yourString.split("\n")[1];
}
catch(ArrayIndexOutOfBoundsException e) {
// Handle the ArrayIndexOutOfBoundsException case
}
// continue your work

TA貢獻1876條經驗 獲得超5個贊
您可以輕松地使用try-catch來避免收到此消息:
try{
string.split("\n")[1];
}catch(ArrayIndexOutOfBoundsException e){
//here for example you can
//print an error message
}
添加回答
舉報