我的程序的设置方式是运行我的代码,并允许用户创建一个新的电影对象,然后将其存储到构造函数中。然后,它提供了创建新电影的选项,然后将其存储在同一电影对象中,该电影最终将覆盖之前创建的电影对象。许多实现都将对象创建放在一个循环中,但这要求将所有多个值一次存储到多个对象中,我不打算这样做。我不确定如何解决这个问题。 这是我的代码 电影课
public class Movie {
private int id;
private String name;
private String description;
private String[] genre;
private String[] actors;
private String[] language;
private String countryOfOrigin;
private Map<String, Integer> ratings;
Movie() {
}
//Constructor
public Movie(int id, String name, String description, String[] genre, String[] actors, String[] language, String countryOfOrigin, Map<String, Integer> ratings) {
this.id = id;
this.name = name;
this.description = description;
this.genre = genre;
this.actors = actors;
this.language = language;
this.countryOfOrigin = countryOfOrigin;
this.ratings = ratings;
}
//setters
public void setid(int id) {
this.id = id;
}
public void setname(String name) {
this.name = name;
}
//getters
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "\nMovie Id: " + id + " \nMovie Name: " + name + "\nMovie Description: " + description + "\nMovie Genre(s): " + Arrays.toString(genre) + "\nMovie Actor(s): " + Arrays.toString(actors) + "\nMovie Language(s): " + Arrays.toString(language) + "\nCountry of Origin: " + countryOfOrigin + "\nRatings: " + ratings +"";
}
}
主班
public class Main{
// --- Private global scanner initialization --- //
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws Exception {
while (loopAgain) {
Random rand = new Random();
int id = rand.nextInt(MAX);
System.out.println("\nCreate Poll");
System.out.println("\nEnter the Movie Name: ");
String name = input.nextLine();
Movie movie1 = new Movie(id, name, description, genre, actors, language, countryOfOrigin, mapRatings);
System.out.println("Create new movie? (y/n): ");
String answer = input.nextLine();
if (answer.equals("y") || answer.equals("Y")) {
loopAgain = true;
}
问题来源:Stack Overflow
创建影片对象后,可以将它们存储在某种容器中。因此,您可以使用ArrayList为例
ArrayList<Movie> movies= new ArrayList<Movie>();。
您可以将其放在while循环上方。然后,在创建对象之后,可以将其添加到容器中,例如可以将其movies.add(movie1)
放在调用构造函数的位置。稍后访问对象,您可以使用movies.get(index)
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。