当我尝试测试运行时,我一直得到第51行的null异常: 歌曲[I] .title伪= Recording.setTitle(); 这个方法似乎很好,所以为什么不设置歌曲[i] .title? 我很擅长导航课程,所以请原谅我这是一个愚蠢的问题。
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);
}
}
}
答案 0 :(得分:1)
您收到此错误,因为虽然您声明并分配了一个包含5个Recording
对象的数组,但您实际上从未实际实例化该数组中的任何对象。
尝试在此处添加一行:
for(int i = 0; i<5; ++i){
songs[i] = new Recording(); //invoke a valid object constructor here
songs[i].title=Recording.setTitle();