2016-06-11 36 views
0

背景排序INT []從字符串[]轉換 - ArrayIndexOutOfBoundsException異常

我一直想立即解決我的程序,這部分有一陣子沒有成功。我基本上想要排序String [],其中每個元素的格式爲:name:number(即john:32)。

進展

到目前爲止,我的代碼將每個元素,並將其添加爲等效int []。然後,我嘗試比較int []中的元素與選擇排序並交換String []中的元素。

問題

我得到java.lang.ArrayIndexOutOfBoundsException我String [],這就是所謂scores。爲什麼是這樣?

scores = sort(scores); //ArrayIndexOutOfBoundsException here 


public static String [] sort(String [] A) { 


     //equivalent array containing only integer part of score[i] 
     int[] tempArray = new int[A.length]; 

     //populate tempArray 
     for(int i = 0; i < A.length; i++) { 
      //acquire numerical part of element 
      //ArrayIndexOutOfBoundsException here******** 
      int num = Integer.parseInt(A[i].split(":")[1]); 
      //add to array 
      tempArray[i] = num; 
     } 


     /* Selection Sort: descendinG */ 

     //compare elements (integer) in tempArray 
     for(int i = 0; i < tempArray.length; i++){ 
     int index = i; 


      //search for integers larger for above index 
       for(int j = i+1; j < tempArray.length; j++){ 
        if(tempArray[j] > tempArray[index]){ 
         index = j; 
        }} 

       //swap elements in scores-array (String) 
       String temp = A[index]; 
       A[index] = A[i]; 
       A[i] = temp; 
     } 

     return A; 
    } 
+2

顯然你有一個字符串,不' 「:」'。 – shmosel

+0

Wooow ...你怎麼知道的? –

+0

這是唯一的可能性。 – shmosel

回答

0

我@shmosel

同意這種說法也許可以幫你剷除害羣之馬

String scoreSplit[] = A[i].split(":"); 
if (scoreSplit.length() == 2){ 
    int num = Integer.parseInt(A[i].split(":")[1]); 
} 
else{ 
    system.out.println("Bad apple with "+ scoreSplit[0]); //some kind of logging 
}