我用对象编写了一个程序,当我尝试运行它时出现NullPointerException错误,但我无法发现代码的确切问题。这是(粗线是日食指向错误的地方):
public class Cinema {
private String cinemaName;
private String Address;
private Room Rooms[];
private Movie Movies[];
private final int MAX_NUM_MOVIES = 20;
private final int MAX_NUM_ROOMS = 5;
private int movieCounter;
private int roomCounter;
public Cinema(String cinemaName, String Address) {
this.cinemaName = cinemaName;
this.Address = Address;
Room Rooms[] = new Room[MAX_NUM_ROOMS];
@SuppressWarnings("unused")
Movie Movies[] = new Movie[MAX_NUM_MOVIES];
movieCounter = 0;
roomCounter = 0;
}
public boolean addMovieToCinema (Movie theMovie) {
if (theMovie == null) {
return false;
}
if (movieCounter < MAX_NUM_MOVIES) {
Movies[movieCounter] = new Movie(theMovie);
movieCounter++;
return true;
} else
return false;
}
}
有什么想法吗?
答案 0 :(得分:2)
而不是分配给这两个成员变量:
private Room Rooms[];
private Movie Movies[];
使用以下两行声明新的局部变量:
Room Rooms[] = new Room[MAX_NUM_ROOMS];
Movie Movies[] = new Movie[MAX_NUM_MOVIES];
修复此问题以初始化您的Rooms
和Movies
班级成员:
Rooms = new Room[MAX_NUM_ROOMS];
Movies = new Movie[MAX_NUM_MOVIES];
答案 1 :(得分:1)
而不是定义:
private Room Rooms[];
private Movie Movies[];
为什么你要定义一个集合!?像:
private Collection<Room> rooms;
private Collection<Movie> movies;
然后,在构造函数中,您必须初始化集合:
this.rooms = new ArrayList<>();
this.movies = new ArrayList<>();
我会说这是Java方式。另请注意,属性名称应为小写。
答案 2 :(得分:0)
这两个数组应该是类字段
private int movieCounter;
private int roomCounter;
private Room[] Rooms = new Room[MAX_NUM_ROOMS];
private Movie[] Movies = new Movie[MAX_NUM_MOVIES];
public Cinema(String cinemaName, String Address) {
this.cinemaName = cinemaName;
this.Address = Address;
movieCounter = 0;
roomCounter = 0;
}
为什么不使用列表存储电影(和房间)?您不必提供硬编码限制。
List<Movie> movies = new ArrayList<>();
public boolean addMovieToCinema(Movie theMovie) {
if (theMovie == null) {
return false;
}
movies.add( theMovie );
return true;
}
一切都变得简单。
答案 3 :(得分:0)
问题是你的构造函数隐藏了你的类成员。
如果你在构造函数中声明private Movie Movies[];
,那么你应该写:Movies = new Movie[MAX_NUM_MOVIES];
当您编写:Movie Movies[] = new Movie[MAX_NUM_MOVIES];
时,您实际上声明了一个构造函数本地的新变量,这就是类成员Movies
为空的原因,因为它不是初始化的。
答案 4 :(得分:0)
我认为错误发生在Cinema类的构造函数中。 它应该是这样的:
public Cinema(String cinemaName, String Address) {
this.cinemaName = cinemaName;
this.Address = Address;
// Remove type before variable to initialize class attribute instead of declaring a new varialble
Rooms = new Room[MAX_NUM_ROOMS];
@SuppressWarnings("unused")
// Remove type before variable to initialize class attribute instead of declaring a new varialble
Movies = new Movie[MAX_NUM_MOVIES];
movieCounter = 0;
roomCounter = 0;
}
将初始化Class属性,并且NullpointerException应该消失。
干杯, 塞巴斯蒂安。
答案 5 :(得分:0)
一种选择是在声明数组时分配内存:
private Room[] Rooms = new Room[MAX_NUM_ROOMS];
或者,如果要在构造函数中分配内存,则需要:
Rooms = new Room[MAX_NUM_ROOMS];