콘텐츠로 이동

미니 프로젝트 세트 3 모범답안: 영화 평점 대시보드

완성 프로그램

public class Main {
    public static String stars(int rating) {
        String result = "";

        for (int i = 0; i < rating; i++) {
            result += "*";
        }

        return result;
    }

    public static void main(String[] args) {
        String[] titles = {"Sky Route", "Moonlight Cafe", "Code Quest", "Ocean Signal", "Last Train"};
        int[] ratings = {4, 5, 3, 5, 2};

        int totalRatings = 0;
        int bestIndex = 0;
        int recommendedMovies = 0;

        for (int i = 0; i < ratings.length; i++) {
            System.out.println(titles[i] + ": " + stars(ratings[i])
                    + " (" + ratings[i] + ")");

            totalRatings += ratings[i];

            if (ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }

            if (ratings[i] >= 4) {
                recommendedMovies++;
            }
        }

        double average = (double) totalRatings / ratings.length;

        System.out.printf("Average rating: %.2f%n", average);
        System.out.println("Top movie: " + titles[bestIndex]);
        System.out.println("Recommended movies: " + recommendedMovies);
    }
}

출력

Sky Route: **** (4)
Moonlight Cafe: ***** (5)
Code Quest: *** (3)
Ocean Signal: ***** (5)
Last Train: ** (2)
Average rating: 3.80
Top movie: Moonlight Cafe
Recommended movies: 3

핵심 포인트

  • titlesratings는 병렬 배열이며, 인덱스 i의 두 값은 같은 영화를 설명한다.
  • ratings[i] > ratings[bestIndex] 조건은 평점이 같을 때 첫 번째 영화를 유지한다.
  • stars는 재사용할 수 있는 보조 메서드이며, 모든 음이 아닌 평점에서 동작하는 반복문을 사용한다.
  • 평균을 계산하기 전 double 형변환이 필요하다.