2011-04-22 77 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其他事情没有帮助。

相关问题