时间:2017-04-03 08:32:22

标签: java arrays class

所以我使用了两个类:

public class Vote {

      public String vote;

       public Vote(String vote) {
            this.vote = vote;
        }

        public String getvote() {
            return vote;
        }
}

然后另一个返回投票数组:

public class Campaign {

    private String title;
    private Vote[] votes;

    public Campaign(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public Vote[] getvotes() {
        return votes;
    }
    }

主要使用此代码:

public class maintest {

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}
}

最后我得到的值为null。但是,如果我添加更多我希望获得更多投票的广告系列,我也希望得到“vote1222”。

2 个答案:

答案 0 :(得分:1)

你应该更好地不使用数组而不是收藏品,考虑一下你不知道会有多少人提前投票的事实......

问题:

投票永远不会在构造函数中初始化,因此通过打印对象为null,而不是...

private List<Vote> votes;

public Campaign(String title) {
    this.title = title;
    this.votes = new ArrayList<Vote>();
}

然后

public void addVote(Vote v) {
    this.votes.add(v);
}


public List<Vote> getvotes() {
    return votes;
}

和实施:

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    first.addVote(pvote);
    System.out.println(first.getTitle() + " " + " " + first.getvotes());
}

编辑:

别忘了在Vote类中覆盖toString方法:)

答案 1 :(得分:1)

您需要在Campaign课程中创建一个setter:

public void setVotes(Vote[] votes) {
    this.votes = votes;
}

main中,您必须调用此方法:

public static void main(String[] args) {
    Campaign first= new Campaign("test");
    Vote pvote = new Vote("vote1222");
    Vote[] votes = new Vote[] { pvote };
    first.setVotes(votes);
    System.out.println(first.getTitle() + " " + " " + Arrays.toString(first.getvotes()));
}

正如您可以在评论中看到的那样,您应该使用Arrays.toString

感谢Fildur:在Vote中,您需要覆盖toString

@Override
public String toString() {
    return vote;
}