【问题标题】:What is causing this Null Pointer Exception?是什么导致了这个空指针异常?
【发布时间】:2015-05-28 17:07:36
【问题描述】:

我正在尝试让歌曲添加和删除功能适用于假设歌曲数据库的假设播放列表。

我第一次调用deleteSong() 函数从播放列表对象中删除一首歌曲时它工作正常。我第二次调用该函数时,在选择要从中删除歌曲的播放列表的索引时,它会尝试运行 selectSong() 函数,在该函数中它启动 for 循环以打印每首歌曲,但显然 songs[] 数组已满空值,或者至少元素 0 是空值,因为它在第一次迭代 (i = 0) 时抛出 NullpointerException

logicalSize 变量很容易解释。它跟踪数组中有多少实际初始化的 Song 对象。

注意:这基本上是为我的播放列表对象(添加和删除播放列表)制作相同功能的复制/粘贴代码,我没有遇到这个问题。

方法如下:

public void deleteSong(int index){
    System.out.println("[INFO] Deleting the selected song...");
    Song[] tempSongs = new Song[songs.length-1];
    tempSongs[tempSongs.length-1] = new Song();
    if (index+1 > songs.length-1){
      System.out.println("[INFO] Song item is last element.");
      for (int i=0;i<tempSongs.length;i++){
          tempSongs[i] = songs[i];
      }
    } else {
      //songs[index+1] = songs[index];
      for (int i=index;i<tempSongs.length;i++){
        if (i == index){
            System.out.println("[INFO] Song: skip index to remove");
        } else {
            tempSongs[i] = songs[i+1];
        }
      }    
  }

  songs = tempSongs;
  logicalSize--;
}

添加歌曲的代码:

public void addSong(Song song)
{

    songs[logicalSize] = new Song();
    songs[logicalSize]= song;
    logicalSize++;
    songCount++;

}

selectSong() 函数:

public int selectSong()
{
    Scanner menu = new Scanner(System.in);
    for (int i=0;i<logicalSize;i++){ 
        System.out.println("[" + i + "] Title: " + songs[i].getName() + " Artist: " + songs[i].getArtist());
    }
    System.out.println("Select a song by entering its song number (0, 1, 2...).");
    int songChoice = menu.nextInt();
    return songChoice;

}

【问题讨论】:

  • 也许添加输出会有所帮助。
  • 请将堆栈跟踪添加到您的问题中。
  • 我知道我不会提供帮助,但您是否尝试过在代码中设置断点并单步执行?

标签: java arrays nullpointerexception


【解决方案1】:

您将newsongs 初始化为一个包含null 歌曲引用的数组。然后,如果您不删除最后一首歌曲,您只需在位置index+1 处开始初始化newsongs。之前的所有条目仍然为空。

除非这是一项作业或学习练习,否则您真的应该了解 Java 的 List 类型及其实现。 Here 是 Java 7 javadoc。

【讨论】:

    【解决方案2】:

    您为什么不尝试使用ArrayList

    您可以定义 Song 的 ArrayList 并使用方法 yourList.add()yourList.remove()。您可以使用索引或对象删除项目

    会是这样的

    ArrayList<Song> yourList = new ArrayList¸<Song>();
    

    ArrayList Oracle

    public E remove(int index)
    public boolean remove(Object o)
    

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多