Menu
Coddy logo textTech

Error Handling

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 45번째.

challenge icon

챌린지

쉬움

잠재적인 문제를 우아하게 처리하기 위해 견고한 오류 처리를 시스템에 추가해 보겠습니다. ErrorHandler라는 클래스를 만들고 다음 메서드들을 구현하세요:

  1. ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex): 입력 인덱스를 검증하고 유효한 경우 적절한 오류 메시지 또는 빈 문자열을 반환합니다.
    • 학생 인덱스가 범위를 벗어난 경우 "Invalid student index"를 반환합니다.
    • 과제 인덱스가 범위를 벗어난 경우 "Invalid assignment index"를 반환합니다.
    • 두 인덱스가 모두 유효한 경우 빈 문자열 ""를 반환합니다.
  2. SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex): 오류 처리를 통해 점수를 안전하게 가져옵니다.
    • 두 인덱스가 모두 유효한 경우 점수를 반환합니다.
    • 인덱스가 잘못된 경우 -999를 반환합니다.
  3. ProcessBatchUpdate(int[][] scoreGrid, int[][] updates): 각 업데이트가 [studentIndex, assignmentIndex, score]인 배치 업데이트를 처리합니다.
    • 실패한 각 업데이트에 대한 오류 메시지의 string[] 배열을 반환합니다.
    • 각 업데이트는 다음 특정 오류 메시지 중 하나로 실패할 수 있습니다:
      • "Invalid update format" — 업데이트에 정확히 3개의 값이 포함되지 않은 경우.
      • "Invalid student index" — 학생 인덱스가 범위를 벗어난 경우.
      • "Invalid assignment index" — 과제 인덱스가 범위를 벗어난 경우.
      • "Invalid score value" — 점수가 유효 범위 (0–100)를 벗어난 경우.
    • 각 오류를 다음 형식으로 포맷하세요: "Error at index X: [specific error message]"
    • 모든 업데이트가 성공한 경우 빈 배열을 반환합니다.
힌트: string[]로 반환하기 전에 오류를 동적으로 수집하려면 List<string> errors = new List<string>();를 사용하세요 — List<string>는 크기가 조정 가능한 배열처럼 작동하며 errors.Add(...)를 호출하여 항목을 추가할 수 있습니다. 마지막에 errors.ToArray()로 변환하세요. 이를 위해 필요한 using System.Collections.Generic; import는 파일 상단에 이미 포함되어 있습니다.

직접 해보기

using System; // 이 줄을 삭제하지 마세요
using System.Collections.Generic;

public class ErrorHandler
{
    public static string ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // 여기에 코드를 작성하세요
        
    }
    
    public static int SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // 여기에 코드를 작성하세요
        
    }
    
    public static string[] ProcessBatchUpdate(int[][] scoreGrid, int[][] updates)
    {
        // 여기에 코드를 작성하세요
        
    }
}

// Required for testing - do not modify
public class DataCollector
{
    public static int[][] CreateScoreGrid(int students, int assignments)
    {
        int[][] scoreGrid = new int[students][];
        for (int i = 0; i < students; i++)
        {
            scoreGrid[i] = new int[assignments];
        }
        return scoreGrid;
    }
    
    public static bool ValidateScore(int score)
    {
        return score >= 0 && score <= 100;
    }
    
    public static int[][] PopulateWithDefaultValues(int[][] scoreGrid)
    {
        for (int i = 0; i < scoreGrid.Length; i++)
        {
            for (int j = 0; j < scoreGrid[i].Length; j++)
            {
                scoreGrid[i][j] = -1;
            }
        }
        return scoreGrid;
    }
}

public class DataEntry
{
    public static int SetStudentScore(int[][] scoreGrid, int studentIndex, int assignmentIndex, int score)
    {
        // 인덱스가 범위를 벗어났는지 확인
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length || 
            assignmentIndex < 0 || assignmentIndex >= scoreGrid[studentIndex].Length)
        {
            return -1;
        }
        
        // 점수를 검증
        if (!DataCollector.ValidateScore(score))
        {
            return -2;
        }
        
        // 점수를 설정
        scoreGrid[studentIndex][assignmentIndex] = score;
        return 0;
    }
    
    public static int UpdateAllScores(int[][] scoreGrid, int[] studentIndices, int assignmentIndex, int score)
    {
        int successCount = 0;
        
        for (int i = 0; i < studentIndices.Length; i++)
        {
            int result = SetStudentScore(scoreGrid, studentIndices[i], assignmentIndex, score);
            if (result == 0)
            {
                successCount++;
            }
        }
        
        return successCount;
    }
}

public class DataAnalyzer
{
    public static double CalculateStudentAverage(int[][] scoreGrid, int studentIndex)
    {
        // 학생 인덱스가 유효한지 확인
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // 유효한 점수들의 합을 계산
        for (int j = 0; j < scoreGrid[studentIndex].Length; j++)
        {
            int score = scoreGrid[studentIndex][j];
            if (score != -1)  // 평가되지 않은 과제를 무시
            {
                sum += score;
                count++;
            }
        }
        
        // 유효한 점수가 없으면 평균 또는 0을 반환
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static double CalculateAssignmentAverage(int[][] scoreGrid, int assignmentIndex)
    {
        // 학생이 있는지 확인
        if (scoreGrid.Length == 0)
        {
            return -1;
        }
        
        // 과제 인덱스가 유효한지 확인
        if (assignmentIndex < 0 || assignmentIndex >= scoreGrid[0].Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // 해당 과제의 유효한 점수들의 합을 계산
        for (int i = 0; i < scoreGrid.Length; i++)
        {
            if (assignmentIndex < scoreGrid[i].Length)
            {
                int score = scoreGrid[i][assignmentIndex];
                if (score != -1)  // 평가되지 않은 과제를 무시
                {
                    sum += score;
                    count++;
                }
            }
        }
        
        // 유효한 점수가 없으면 평균 또는 0을 반환
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static int[] FindHighestScore(int[][] scoreGrid)
    {
        int highestStudentIndex = 0;
        int highestAssignmentIndex = 0;
        int highestScore = -1;
        
        // 최고 점수를 검색
        for (int i = 0; i < scoreGrid.Length; i++)
        {
            for (int j = 0; j < scoreGrid[i].Length; j++)
            {
                int currentScore = scoreGrid[i][j];
                if (currentScore > highestScore)
                {
                    highestScore = currentScore;
                    highestStudentIndex = i;
                    highestAssignmentIndex = j;
                }
            }
        }
        
        return new int[] { highestStudentIndex, highestAssignmentIndex, highestScore };
    }
}

논리 및 흐름의 모든 레슨