设计一个包含有关电影信息的类电影。该类具有以下属性(成员变量):
该类应具有以下成员函数:
当我运行该程序时,它没有显示正确的平均值,例如,如果我将ice-age评为3和4,它的平均值应该是3.5,而是它给出了我的最后一个等级,即4。是我的两种方法:
public static void addRating(int rating)
{
Scanner keyboard = new Scanner(System.in);
movieRating = rating;
numberOfPeopleRated = 0;
switch(movieRating)
{
case 1:
numberOfPeopleRated++;
break;
case 2:
numberOfPeopleRated++;
break;
case 3:
numberOfPeopleRated++;
break;
case 4:
numberOfPeopleRated++;
break;
case 5:
numberOfPeopleRated++;
break;
}
System.out.println("You rated " + movieName + " a " + movieRating);
}
public static void getAverage()
{
totalMovieRating += movieRating;
double averageRating = totalMovieRating / numberOfPeopleRated;
System.out.println("The average Rating is " + averageRating);
}
答案 0 :(得分:1)
你在那里遇到了一些语义(逻辑)错误。
numberOfPeopleRated
每次都设为0。movieRating
添加到totalMovieRating
错误的地方!修正后的版本看起来有点像这样:
public static void addRating(int rating) {
if (rating >= 1 && rating <= 5) {
numberOfPeopleRated++;
totalMovieRating += rating;
System.out.println("You rated " + movieName + " a " + rating);
} else {
System.out.println("Wrong rating");
}
}
public static void getAverage() {
double averageRating = ((double)totalMovieRating) / numberOfPeopleRated;
System.out.println("The average Rating is " + averageRating);
}