我正在尝试用java创建一个文本"数据库",该数据库接受用户输入来填充对象(电影),并将它们存储在数据库类中的数组中。这是我的"电影"课,没有所有的"集"one_answers"集":
public class Movie
{
private int fileSize,duration;
private String movieNamez,director;
static int numberOfMovies;
//--------------------------------------------------------------------------------------
// constructor method
//--------------------------------------------------------------------------------------
public Movie()
{
movieNamez = "No title - SLOT FREE";
director = "No director - SLOT FREE";
fileSize = 0;
duration = 0;
}
//--------------------------------------------------------------------------------------
public void setmovieNumber(int movieNumber)
{
this.numberOfMovies = movieNumber;
}
public int getmovieNumber()
{
return this.numberOfMovies;
}
//--------------------------------------------------------------------------------------
public void setmovieName(String newmovieNamez)
{
this.movieNamez = newmovieNamez;
}
public String getmovieName()
{
return this.movieNamez;
}
//--------------------------------------------------------------------------------------
这是我的MovieDatabase类的相关部分:
public class MovieDatabase
{
//--------------------------------------------------------------------------------------
int maxMovies = 4;
// ArrayList<Movie> allMovies = new ArrayList<Movie>();
Movie [] allMovies = new Movie[maxMovies];
//md.addmovieData(movieCount,movieName,director,fileSize,duration);
//--------------------------------------------------------------------------------------
public void addmovieData(int movieNum, String movieName,String director, int fileSize, int duration)
{
allMovies[movieNum].setmovieName(movieName);
allMovies[movieNum].setDirector(director);
allMovies[movieNum].setfileSize(fileSize);
allMovies[movieNum].setDuration(duration);
}
private void printMovie(Movie movie){
System.out.println("Movie Name: "+movie.getmovieName());
System.out.println("Movie Director: "+movie.getDirector());
System.out.println("Movie File Size: "+movie.getfileSize());
System.out.println("Movie Duration: "+movie.getDuration());
System.out.println();
}
//--------------------------------------------------------------------------------------
最后是用户界面类中的行,在这些行中输入并发送到数据库(然后发送到电影对象)。
MovieDatabase md = new MovieDatabase();
int movieCount=0
md.addmovieData(movieCount,movieName,director,fileSize,duration);
movieCount++;
我试图将要存储的信息作为电影对象发送,同时发送一个整数,告诉我电影的数量,然后当movieCount迭代时,我使用该迭代来告诉程序电影应该存储在数组中的哪个数字(位置)下。我实现数组的方法出了问题,所以我得到了一个空指针异常,但经过数小时(我知道这很可耻)的摆弄和尝试其他方法(包括arrayList),我似乎无法理解我做错了什么。提前感谢你们的时间,伙计们,这让我头疼。
当您创建一个Array对象时,它的所有状态都会初始化为默认值,在您的情况下为null。
在addmovieData
方法中,您必须首先创建一个Movie
对象并将其推送到allMovies
。类似这样的东西-
Movie movie = new Movie();
allMovies[movieNum] = movie;
allMovies[movieNum].setmovieName(movieName);
allMovies[movieNum].setDirector(director);
allMovies[movieNum].setfileSize(fileSize);
allMovies[movieNum].setDuration(duration);