【发布时间】:2019-12-10 05:35:42
【问题描述】:
在我的程序中,我正在读取一个包含电影信息并提取电影 ID 和演员姓名的文件。然后我将每部电影的电影 ID 和演员名称存储在一个对象中,并将这些对象添加到一个数组列表中。然后我提示用户输入演员姓名,我想检查整个列表以查看演员是否在列表中。
我使用 while 循环来执行此操作:while(!cast.contains(actor1)),但是,我将用户的输入与列表中的对象进行比较,而不是与对象关联的参与者名称。
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class Assignment2 {
public static void main(String[] args) throws Exception {
File movieFile = null;
if(args.length > 0)
movieFile = new File(args[0]);
Scanner sc = new Scanner(movieFile);
String movieLine, actorName;
int movieID, index1, index2, count = 0;
ArrayList<MovieCast> cast = new ArrayList<>();
MovieCast listObj;
sc.nextLine(); // skip first line (movie_id, title, cast, crew)
while(sc.hasNext()) {
movieLine = sc.nextLine();
index1 = movieLine.indexOf(',');
movieID = Integer.parseInt((movieLine.substring(0, index1)).trim());
index1 = movieLine.indexOf("cast_id"); // in case movie contains name
if(index1 > -1) {
index1 = movieLine.indexOf("name", index1);
index1 += 10; // moved to beginning of actor's name
index2 = movieLine.indexOf(',', index1);
actorName = movieLine.substring(index1, index2 - 2);
listObj = new MovieCast(movieID, actorName);
cast.add(listObj);
count++;
}
}
for(int i = 0; i < 10; i++) // for testing
System.out.println(cast.get(i).movieID + "\t" + cast.get(i).actorName);
sc.close();
Scanner scan = new Scanner(System.in);
String actor1 = " ";
while(!actor1.isEmpty()) {
System.out.print("Enter actor 1's name or enter nothing to stop: ");
actor1 = scan.nextLine();
if(actor1.length() == 0)
return;
while(!cast.contains(actor1)) {
System.out.println("No such actor.");
System.out.println("Enter actor 1's name or enter nothing to stop: ");
actor1 = scan.nextLine();
if(actor1.length() == 0)
return;
}
}
}
}
我想知道如何访问对象中的演员名称以进行比较。
【问题讨论】: