콘텐츠로 이동

미니 프로젝트 세트 2 모범답안: 주차장 리포트

완성 프로그램

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] hours = new int[5];

        for (int i = 0; i < hours.length; i++) {
            System.out.print("Car " + (i + 1) + " hours: ");
            hours[i] = input.nextInt();
        }

        int totalHours = 0;
        int totalFees = 0;
        int longStayCars = 0;

        for (int i = 0; i < hours.length; i++) {
            totalHours += hours[i];

            if (hours[i] > 5) {
                totalFees += 8;
                longStayCars++;
            } else if (hours[i] >= 3) {
                totalFees += 5;
            } else {
                totalFees += 3;
            }
        }

        double average = (double) totalHours / hours.length;

        System.out.println("Total hours: " + totalHours);
        System.out.println("Total fees: $" + totalFees);
        System.out.println("Long-stay cars: " + longStayCars);
        System.out.printf("Average stay: %.2f hours%n", average);

        input.close();
    }
}

예시 입력에 대한 출력

Car 1 hours: Car 2 hours: Car 3 hours: Car 4 hours: Car 5 hours:
Total hours: 20
Total fees: $27
Long-stay cars: 2
Average stay: 4.00 hours

핵심 포인트

  • hours.length를 사용하면 반복문의 한계를 직접 숫자로 쓰지 않아도 된다.
  • 배열을 한 번 순회하면서 전체 시간, 요금, 장기 주차 수를 함께 갱신한다.
  • (double) totalHours는 정수 나눗셈을 방지한다.
  • 조건문은 $8 규칙을 $5, $3 규칙보다 먼저 적용한다.