我很困惑ArrayIndexOutOfBoundsException
我越來越感到困惑。使用分割方法後,我無法對數組TempCity
的值進行分配。對字符串進行拆分操作後發生ArrayIndexOutOfBoundsException錯誤
String[] TempCity = new String[2];
cityNames = props.getProperty("city.names").split(",");
cities = new City [cityNames.length];
//I have also tried String[] TempCity without succes
for (int i = 0; i < cities.length; i++) {
System.out.println(TempCity[1]); //OK
TempCity = cityNames[i].split(":"); // returns String array, problem is when Strings look like "something:" and do not receive second value of array
System.out.println(TempCity[1]); //Error
try{
if (TempCity[1] == null){}
}
/* I was thinking about allocating second array's value in catch */
catch (Exception e)
{
TempCity[1] = new String();
//I'm getting Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 1
}
try{
cities[i] = new City(TempCity[0], TempCity[1]);
...
感謝您的幫助! 現在,我的解決方案包括創建另一個字符串數組:
String[] temp = new String[2];
String[] tempCity = new String[2];
temp = cityNames[i].split(":");
for (int j = 0; j < temp.length; j++){
tempCity[j] = temp[j];
}