2011-04-22 80 views
1

我很困惑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]; 

      } 

回答

4

split()不返回尾隨的空字符串。你必須在你的代碼中允許這個。 使用split()的雙參數版本並傳遞一個負數作爲第二個參數。

根據JavaDoc:

此方法類似於調用 兩個參數分割方法與 給定的表達式和一個限制參數的零 。尾隨的空字符串是 因此不包含在 結果數組中。

3

這意味着split()返回只有一個元素的數組,你要訪問的第二個。評估TempCity.length將告訴你,它是'1'

打印出TempCity[0],看看是什麼;它將會是你的整個輸入字符串(cityNames [i])。

0

String[] TempCity = new String[2];如果你要覆蓋TempCity其他事情沒有幫助。

相關問題