2016-06-11 6 views
0

CONTEXTSortiert int [] von String konvertiert [] - ArrayIndexOutOfBoundsException

ich für eine Weile diesen Teil meines Programms zu beheben habe versucht, jetzt ohne viel Erfolg. Ich möchte im Wesentlichen eine String [] sortieren, wobei jedes Element im Format: name:number (d. H. john:32) ist.

PROGRESS

Bisher teilt mein Code jedes Element und fügt sie zu einem gleichwertigen int []. Ich versuche dann, die Elemente in der int [] mit Auswahlsortierung zu vergleichen und die Elemente in der String [] auszutauschen.

PROBLEM

ich java.lang.ArrayIndexOutOfBoundsException für meine String [] bin immer, die scores genannt wird. Warum ist das?

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

Offensichtlich haben Sie eine Zeichenfolge ohne ' ":"'. – shmosel

+0

Wooow ... woher weißt du das? –

+0

Es war die einzige Möglichkeit. – shmosel

Antwort

0

Ich stimme @shmosel mit

wahrscheinlich helfen, diese können Sie die schlechten Apfel auszurotten

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 
} 
Verwandte Themen