【发布时间】:2017-01-13 02:21:21
【问题描述】:
我有一个复习课,用于在另一个名为游戏信息的课中创建一个数组。
我创建了一个 setter 方法,用于向 gameInfo 的评论数组添加评论。我有 addReview 函数来搜索这个游戏评论,如果有一个空的评论槽,然后将评论输入添加到评论数组中。我只是想确保 addReview 方法的逻辑正确。
class Review {
//review class variables
public String reviewText;
public int numberOfStars;
//review class constructor
public Review(String reviewText, int numberOfStars) {
this.reviewText=reviewText;
this.numberOfStars=numberOfStars;
}
}
class GameInfo {
//game info class variables
private String title;
private Review[] reviews = new Review[10];
//game info class constructor
public GameInfo(String title, Review[] reviews) {
this.title=title;
this.reviews = reviews;
}
//setter to add single review to reviews[]
public void addReview(Review r) {
int i;
for(i = 0; i < this.reviews.length; i++) {
if(this.reviews[i] == null) {
this.reviews[i].reviewText = r.reviewText;
this.reviews[i].numberOfStars = r.numberOfStars;
break;
}
}
}
}
【问题讨论】:
-
T.J. 的回答说明了为什么这段代码会出现异常。但我也质疑这是否真的是你想做的事情。为了使您的解决方案有效,构造
GameInfo的代码还必须构建一个null插槽数组,然后再添加,或者可能是一个包含一些评论和一堆其他null插槽的数组。这似乎是一种 C 的做事方式。请查看ArrayList,这是一种允许动态向数组添加元素的更好方法。