I have watched videos, searched this websites and many others, but nothing really helps. This is the first time I have used 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. 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 problem I am having is it won't allow me to add to the 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
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 :
public String toString(){
return "ID : "+this.usrID+", Comment : "+this.usrComment;
}
That way, 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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.