안녕하세요 지코딩입니다.
오늘은 「java_an_introduction_to_problem_solving_and_programming_6th_edition」 366페이지 12번 문제를 풀어보겠습니다.
<문제>
getter, setter 메소드를 사용하여 movie 클래스를 만들어보겠습니다.
public class Movie {
private String name, mpaaRating;
public double rated1 = 0;
public double rated2 = 0;
public double rated3 = 0;
public double rated4 = 0;
public double rated5 = 0;
public double sum = 0;
public void setName(String name) {
this.name = name;
}
public void setMpaaRating(String mpaaRating) {
this.mpaaRating = mpaaRating;
}
public String getName() {
return name;
}
public String getMpaaRating() {
return mpaaRating;
}
public void addRating(int rate) {
if(rate>=1 && rate<=5) {
if(rate == 1)
rated1++;
else if(rate == 2)
rated2++;
else if(rate == 3)
rated3++;
else if(rate == 4)
rated4++;
else if(rate == 5)
rated5++;
sum+=rate;
}
}
public double getAverage(){
return (sum/(rated1+rated2+rated3+rated4+rated5));
}
public boolean equals(Movie m) {
return (this.name.equals(m.name) &&
this.mpaaRating.equals(m.mpaaRating) &&
this.rated1 == m.rated1 &&
this.rated2 == m.rated2 &&
this.rated3 == m.rated3 &&
this.rated4 == m.rated4 &&
this.rated5 == m.rated5);
}
}
이 클래스를 메인함수에서 실행시켜보겠습니다.
public class MovieDemo {
public static void main(String[] args) {
boolean equality;
double average1, average2;
Movie movie1 = new Movie();
movie1.setName("firstmovie");
movie1.setMpaaRating("PG");
movie1.addRating(1);
movie1.addRating(3);
movie1.addRating(2);
movie1.addRating(4);
movie1.addRating(4);
average1 = movie1.getAverage();
System.out.println("Average rating of firstmovie: " + average1);
Movie movie2 = new Movie();
movie2.setName("secondmovie");
movie2.setMpaaRating("PG-13");
movie2.addRating(1);
movie2.addRating(3);
movie2.addRating(3);
movie2.addRating(4);
movie2.addRating(4);
average2 = movie2.getAverage();
System.out.println("Average rating of secondmovie: " + average2);
equality = movie2.equals(movie1);
System.out.println(equality);
}
}
[java] 상속(Inheritance) 연습문제 (0) | 2021.07.07 |
---|---|
[java] 배열 연습문제 #2 (0) | 2021.07.06 |
[java] 배열 연습문제 #1 (0) | 2021.07.05 |
[java] 클래스(class) 연습문제 #2 (0) | 2021.06.29 |
[java] 클래스(class) 연습문제 #1 (0) | 2021.06.28 |
댓글 영역