[英]Issues adding to ArrayLists
I have watched videos, searched this websites and many others, but nothing really helps. 我看过视频,搜索过该网站以及许多其他网站,但没有任何帮助。 This is the first time I have used ArrayLists. 这是我第一次使用ArrayLists。 If I have the ArrayList as String it's fine, but as soon as I set Comment (which is the class) it no longer works. 如果我将ArrayList作为String可以,但是一旦我设置Comment(这是该类),它就不再起作用。 But the tutor has implied that this is how it's meant to be used. 但是导师暗示这就是它的用法。 I have two other classes that need access to it plus obviously the main method. 我还有另外两个需要访问它的类,当然还有main方法。
Main problem I am having is it won't allow me to add to the arraylist. 我遇到的主要问题是它不允许我添加到arraylist。 And I'm stumped and it's probably really simple. 而且我很困惑,这可能真的很简单。
public class Comment {
// somehow need to link it to the game/app
private ArrayList<Comment> Reply = new ArrayList<Comment>();
private String usrComment;
private String usrID;
public Comment() {
}
public Comment(String usrID, String usrComs) {
this.usrComment = usrComs;
this.usrID = usrID;
}
public void addReview(String addRev) {
this.Reply.add(addRev); // not working
}
public void addReply(String addRep) {
Reply.add(addRep); // not working and I cannot figure it out
}
public void printRep() {
for (Comment comment : Reply) {
System.out.println(comment);
}
}
}
The problem is that you are trying to add a String
but the array list is expecting a Comment
问题是您尝试添加String
但是数组列表中需要Comment
public void addReview(String addRev) {
// Reply is an ArrayList<Comment> of Comments not of Strings
// this.Reply.add(addRev); // not working
// you can create a new Comment and then add that comment
this.Reply.add(new Comment("userId", addRev));
}
public void addReply(String addRep) {
// same here
// Reply.add(addRep); // not working and I cannot figure it out
// you can create a new Comment and then add that comment
this.Reply.add(new Comment("userId", addRep));
}
You could modify your code to do the following : 您可以修改代码以执行以下操作:
/**
*id - ID of the user reviewing the comment
*review - The review comment made by the user
*/
public void addReview(String id, String review) {
this.Reply.add(new Comment(id,review));
}
/**
*id - ID of the user replying
*review - The reply comment made by the user
*/
public void addReply(String id, String reply) {
this.Reply.add(new Comment(id,reply));
}
To print the comment, you could add a toString method as follows : 要打印注释,可以添加toString方法,如下所示:
public String toString(){
return "ID : "+this.usrID+", Comment : "+this.usrComment;
}
That way, System.out.println(comment); 这样,System.out.println(comment); will print : 将打印:
ID : 123412, Comment : This is a comment
for an object instantiated like this : 对于这样实例化的对象:
Comment comment = new Comment("123412", "This is a comment")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.