[英]Issues adding to ArrayLists
我看過視頻,搜索過該網站以及許多其他網站,但沒有任何幫助。 這是我第一次使用ArrayLists。 如果我將ArrayList作為String可以,但是一旦我設置Comment(這是該類),它就不再起作用。 但是導師暗示這就是它的用法。 我還有另外兩個需要訪問它的類,當然還有main方法。
我遇到的主要問題是它不允許我添加到arraylist。 而且我很困惑,這可能真的很簡單。
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);
}
}
}
問題是您嘗試添加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));
}
您可以修改代碼以執行以下操作:
/**
*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));
}
要打印注釋,可以添加toString方法,如下所示:
public String toString(){
return "ID : "+this.usrID+", Comment : "+this.usrComment;
}
這樣,System.out.println(comment); 將打印:
ID : 123412, Comment : This is a comment
對於這樣實例化的對象:
Comment comment = new Comment("123412", "This is a comment")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.