You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发SpotifyPlaylist类时top10热门歌曲统计方法失效如何修复

修复方案

1 topTen方法错误原因

  • 循环逻辑错误:while循环执行第一次就直接break,没有遍历播放列表内所有歌曲,仅处理了第一首歌
  • 排名逻辑缺失:只对比了top10数组的第一个位置,没有循环遍历已有的top10位置完成排序插入
  • 边界情况未处理:当播放列表歌曲不足10首时,top10数组中剩余的-1下标会触发空指针异常

2 修复后的topTen方法代码

/**
 * 打印播放量最高的10首热门歌曲
 */
public void topTen() {
    // 存播放量top10的歌曲下标,初始值-1代表空位置
    int[] top10 = new int[10];
    for (int i = 0; i < 10; i++) {
        top10[i] = -1;
    }

    // 遍历所有歌曲
    for (int i = 0; i < first; i++) {
        int currentPlayCount = numPlaysAtIndex(i);
        int holdIndex = i;

        // 遍历top10数组找插入位置
        for (int place = 0; place < 10; place++) {
            // 空位置直接插入
            if (top10[place] == -1) {
                top10[place] = holdIndex;
                break;
            }
            // 当前歌曲播放量比该位置存储的歌曲高,替换后继续把被替换的往后排
            int placePlayCount = numPlaysAtIndex(top10[place]);
            if (currentPlayCount > placePlayCount) {
                int temp = top10[place];
                top10[place] = holdIndex;
                holdIndex = temp;
                currentPlayCount = numPlaysAtIndex(holdIndex);
            }
        }
    }

    // 打印结果,跳过空位置
    for (int index : top10) {
        if (index != -1) {
            System.out.println(playlist[index]);
        }
    }
}

3 其他已知问题修复

你当前的remove方法也存在逻辑错误:删除歌曲时移动元素的逻辑混乱,且没找到对应歌曲时也会错误将first减1,修复后代码如下:

/**
 * 根据歌曲标题删除指定歌曲
 * @param title 要删除的歌曲标题
 */
public void remove(String title){
    for(int i = 0; i < first; i++){
        if(playlist[i].getTitle().equals(title)){
            // 找到歌曲后将后面的元素往前移一位
            for(int j = i; j < first - 1; j++){
                playlist[j] = playlist[j+1];
            }
            // 最后一位设为null,有效长度减1
            playlist[first - 1] = null;
            first -= 1;
            // 匹配到就跳出,避免重复删除同标题歌曲
            break;
        }
    }
}

内容的提问来源于stack exchange,提问作者sadJavaStudent222222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:57:00