所以这是我的代码。当我运行测试时,它会给出索引超出范围的错误并高亮显示if
(songList.get(j).getDuration()<(songList.get(j-1).getDuration()) )
{
部分代码。我该如何解决??? import java.util.ArrayList;
/**
* 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 :(得分:0)
您尝试使用ArrayList
j
循环在for
的末尾开始。
for (int j = songList.size()-1; j > i ; ++j)
但是,这会增加j
,因此您会跑到ArrayList
的末尾。
相反减少了j
,所以你不会跑到最后,所以循环最终会j
遇到i
并终止:
// HERE
for (int j = songList.size()-1; j > i ; --j)
您的其他j
for
循环已正确--j
。