我正在做一个为电影创建虚拟数据库的项目。我有两个类:MovieEntry(用于单个电影条目)和MovieDatabase(包含数据库并允许添加内容的较大类,等等)。我遇到了一些错误,第一个错误是在searchTitle方法中说数据库是不兼容的类型。谁能告诉我如何进行这些for-each循环吗?我读了这本书,以为ArrayList应该放在那儿,但显然不是。
**import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<MovieEntry> searchTitle(String substring){
for (String title : Database)
System.out.println(title);
return null;
}
public ArrayList<MovieEntry> searchGenre(String substring){
for (String genre : Database)
System.out.println(genre);
return null;
}
public ArrayList<MovieEntry> searchDirector (String str){
for (String director : Database)
System.out.println(director);
return null;
}
public ArrayList<MovieEntry> searchYear (int yr){
ArrayList <String> yearMatches = new ArrayList<String>();
for (String s : Database)
s.getYear();
if(yearMatches.contains(y) == false){
yearMatches.add(y);
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <String> Matches = new ArrayList<String>();
for(Student s : movies);
Matches.add();
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File(movies));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(FileNotFoundException error){
System.out.println("File not found.");
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
String g;
ArrayList <String> gList = new ArrayList<String>();
for(Student s : movies){
String g = s.getGenre();
if(gList.contains(g) == false){
gList.add(g);
}
return gList.size();
}
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(Student s : movies){
String d = s.getDirector();
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
}
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
}**
最佳答案
foreach变量的类型(在String
方法中为循环的情况下,searchTitle
)必须与参数化类型(MovieEntry
)的类型参数(ArrayList<MovieEntry>
)兼容。显然不是这样。以下foreach循环将起作用:
for (MovieEntry title : Database) {
System.out.println(title);
}
请考虑遵循对字段使用小写名称的约定,即使用
ArrayList<MovieEntry>
而不是database
之类的名称来调用Database
。