2011-04-22 2 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 내에서

:

이 방법은 작동 주어진 표현과 인수 제한 제로의 와 2 개의 인수를 취하는 split 메소드를 호출했을 경우와 같게. 따라서 빈 문자열 뒤에 오는 문자는 이고 결과 배열에는 에 포함되지 않습니다.

3

그것은 split()은 단일 요소 배열을 반환한다는 것을 의미하고, 두 번째 하나에 액세스하려고하고 있습니다. TempCity.length을 평가하면 '1'이라고 표시됩니다.

TempCity[0]을 인쇄하고 그 내용을 확인하십시오. 그것은 전체 입력 문자열 (cityNames [i])이 될 것입니다.

0

String[] TempCity = new String[2];TempCity을 다른 것으로 덮어 쓰려면 도움이되지 않습니다.

관련 문제