java - 这个错误是什么意思 : java. lang.NullPointerException

标签 java arrays class nullpointerexception

当我尝试测试运行时,我不断收到第 51 行的空异常: 歌曲[i].title=Recording.setTitle(); 该方法似乎调用得很好,那么为什么没有设置ongs[i].title呢? 我对导航类(class)还很陌生,所以如果这是一个愚蠢的问题,请原谅我。

import java.util.Scanner;

class Recording {
    String title;
    String artist;
    String time;

     String getTitle(){
        return title;
     }


    String getArtist(){
        return artist;
    }

    String getTime(){
        return time;
    }

     static String setTitle(){
        Scanner title_input = new Scanner(System.in);
        System.out.println("What is the title of your recording?");
        String title_received = title_input.nextLine();
        return title_received;
    }

     String setArtist(){
        Scanner artist_input = new Scanner(System.in);
        System.out.println("Who is the artist of your recording?");
        String artist_received = artist_input.nextLine();
        return artist_received;
    }

     String setTime(){
        Scanner time_input = new Scanner(System.in);
        System.out.println("How long is your recording of your recording?");
        String time_received = time_input.nextLine();
        return time_received;
    }
}
public class RecordingSort {

    public static void main(String[] args) {


            Recording[] songs = new Recording[5];

            for(int i = 0; i<5; ++i){
                songs[i].title=Recording.setTitle();
                System.out.println(songs[i].title);
            }

    }

}

最佳答案

您收到此错误是因为尽管您声明并分配了 5 个 Recording 对象的数组,但您从未实际实例化该数组中的任何对象。

尝试在此处添加一行:

for(int i = 0; i<5; ++i){
                songs[i] = new Recording(); //invoke a valid object constructor here                                  
                songs[i].title=Recording.setTitle();

关于java - 这个错误是什么意思 : java. lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29439744/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 如何读取/访问名称 :values of Objects stored within an Array?

Ruby 轻松访问类变量

c# - 是否有内置的方法来识别类的实例?

java - 动态规划?

javascript - JS 否则/否则如果

java - 在记录器中获取堆栈跟踪

swift - 给定一个 Swift 对象的实例,我们可以测试它的类是否存在类函数吗?

java - Apache Thrift 2-way SSL 相互认证

java - 在java中使用登录加载网页