在java中将值从文件传递到对象
我试图读取一个存储了不同电影及其属性的文件,然后我想创建一个称为电影的对象。这是我的电影课 公映{在java中将值从文件传递到对象,java,Java,我试图读取一个存储了不同电影及其属性的文件,然后我想创建一个称为电影的对象。这是我的电影课 公映{ static Scanner userInputInt = new Scanner(System.in); static Scanner userInputString = new Scanner(System.in); static Scanner userInputDouble = new Scanner(System.in); int ID; String name; String g
static Scanner userInputInt = new Scanner(System.in);
static Scanner userInputString = new Scanner(System.in);
static Scanner userInputDouble = new Scanner(System.in);
int ID;
String name;
String genre;
int length;
int year;
String director;
int sumOfRatings;
int totalRatings;
double averageRatings;
int totalViews;
public static movie[] readMovies() {
movie[] tempMovie = new movie[100];
int line = 0;
try{
BufferedReader myFile = new BufferedReader (new FileReader("moviefile.txt"));
String sCurrentLine;
while ((sCurrentLine = myFile.readLine()) != null){
tempMovie [line].ID = Integer.parseInt(sCurrentLine.split("\t") [0]);
tempMovie [line].name = sCurrentLine.split("\t") [1];
tempMovie [line].genre = sCurrentLine.split("\t") [2];
tempMovie [line].length = Integer.parseInt(sCurrentLine.split("\t") [3]);
tempMovie [line].year = Integer.parseInt(sCurrentLine.split("\t") [4]);
tempMovie [line].director = sCurrentLine.split("\t") [5];
tempMovie [line].sumOfRatings = Integer.parseInt(sCurrentLine.split("\t") [6]);
tempMovie [line].totalRatings = Integer.parseInt(sCurrentLine.split("\t") [7]);
tempMovie [line].averageRatings = Double.parseDouble(sCurrentLine.split("\t") [8]);
tempMovie [line].totalViews = Integer.parseInt(sCurrentLine.split("\t") [9]);
line++;
}
myFile.close(); }
catch (IOException error){
System.out.println("File cannot be read.");
}
movie[] newMovie = new movie[line];
System.arraycopy(tempMovie, 0, newMovie, 0, line);
return newMovie;
}
}
当我试图调用另一个类中的对象时,我得到以下错误:;无法分配字段ID,因为tempMovie[line]为空。但是,使用while循环时,它不应该迭代tempmoine数组的次数超过文件中的条目数。有人知道怎么解决吗?首先需要初始化数组中的对象,您只是创建了一个数组,而不是位置线中的对象:
...
while ((sCurrentLine = myFile.readLine()) != null){
tempMovie[line] = new movie();
...
}
....
PS:请检查您的Java代码。您没有遵循Java代码约定。
e、 g:例如,类名必须以大写字母开头,比如电影
此外,将其他层的IO逻辑分开是一种很好的做法。最好在模型类之外的类中进行IO操作