2014-04-03 113 views
0

所以這是我的代碼。當我運行測試時,它會給我索引超出界限的錯誤,並且如果高於這個範圍,那麼將會導致索引超出範圍。我該如何解決??? import java.util.ArrayList;需要幫助Index列表出界列表異常

/** 
* Write a description of class SongList here. 
* 
* @author (your name) 
* @version (a version number or a date) 
*/ 
public class SongList 
{ 

    private ArrayList <Song> songList; 
/** 
    * Constructor for objects of class SongList 
    */ 
    public SongList() 
    { 
    songList = new ArrayList<Song>(); 

} 

public boolean addSong(Song s) 

     { 

     songList.add(s); 

     return true; 
     } 

    public int findSong(String title) 
    { 
     for (int i=0; i < songList.size(); ++i) 
     { 
     if (songList.get(i).getTitle().compareTo(title) == 0) 
     return i; 
    } 
    return -1 ; 


} 

public void swapSong(int i, int j) 
    { 

     Song[ ] ai = new Song [100]; 
     Song temp = ai[i]; 
     ai[i] = ai[j]; 
     ai[j] = temp;  
    } 


public void sortByDuration() 
{ 
for(int i=0; i < songList.size()-1; ++i) 
    { 
     for (int j = songList.size()-1; j > i ; ++j) 
    { 
     if (songList.get(j).getDuration()<(songList.get(j-1).getDuration()) ) 
     { 

      swapSong(j,j-1); 

     } 


    } 

} 


} 


public void sortByWriter() 
{ 
for(int i=0; i < songList.size()-1; ++i) 
    { 
     for (int j = songList.size()-1; j > i ; --j) 
    { 
    if(songList.get(j).getWriter().compareTo(songList.get(j-i).getWriter())<0) 
    { 


    swapSong(j,j-1); 

} 
} 
} 
} 



public void sortByGenre() 
{ 
    for(int i=0; i < songList.size()-1; ++i) 
    { 
     for (int j = songList.size()-1; j > i ; --j) 
    { 
    if (songList.get(j).getGenre().compareTo(songList.get(j-1).getGenre())<0) 
    swapSong(j,j-1); 
} 
}} 



public void sortByYear() 
{ 
    for(int i=0; i < songList.size()-1; ++i) 
    { 
     for (int j = songList.size()-1; j > i ; --j) 
    { 
if (songList.get(j).getYear()<(songList.get(j-1).getYear())) 
swapSong(j,j-1); 

} 
}} 


public int getSize() 
{ 
    return songList.size(); 

} 
} 

回答

0

您正試圖在你的ArrayList與您jfor循環年底開工。

for (int j = songList.size()-1; j > i ; ++j) 

然而,這增加j所以你跑出ArrayList結束。

減少j代替,這樣你就不會流失結束,所以循環最終將有j滿足i和終止:

//          HERE 
for (int j = songList.size()-1; j > i ; --j) 

你的其他jfor循環已經做--j正確。