gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:42:09 29 4
gpt4 key购买 nike

当我尝试测试运行时,我不断收到第 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com