오류 처리
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨. 66개 중 45번째.
챌린지
쉬움잠재적인 문제를 원활하게 처리할 수 있도록 강력한 오류 처리를 사용해 시스템을 개선해 봅시다. 다음 메서드를 포함하는 ErrorHandler라는 클래스를 만드세요:
ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex): 입력 인덱스를 검증하고, 적절한 오류 메시지를 반환하거나 유효한 경우 빈 문자열을 반환합니다.- student 인덱스가 범위를 벗어나면
"Invalid student index"를 반환합니다. - assignment 인덱스가 범위를 벗어나면
"Invalid assignment index"를 반환합니다. - 두 인덱스가 모두 유효하면 빈 문자열
""을 반환합니다.
- student 인덱스가 범위를 벗어나면
SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex): 오류 처리를 사용하여 안전하게 점수를 가져옵니다.- 두 인덱스가 모두 유효하면 점수를 반환합니다.
- 인덱스 중 하나라도 유효하지 않으면
-999를 반환합니다.
ProcessBatchUpdate(int[][] scoreGrid, int[][] updates): 각 업데이트가[studentIndex, assignmentIndex, score]인 일괄 업데이트를 처리합니다.- 실패한 각 업데이트에 대한 오류 메시지의
string[]배열을 반환합니다. - 각 업데이트는 다음과 같은 특정 오류 메시지 중 하나와 함께 실패할 수 있습니다:
- 업데이트에 정확히 3개의 값이 포함되어 있지 않으면
"Invalid update format"입니다. - student 인덱스가 범위를 벗어나면
"Invalid student index"입니다. - assignment 인덱스가 범위를 벗어나면
"Invalid assignment index"입니다. - 점수가 유효한 범위(0-100)를 벗어나면
"Invalid score value"입니다.
- 업데이트에 정확히 3개의 값이 포함되어 있지 않으면
- 각 오류를 다음 형식으로 지정합니다:
"Error at index X: [specific error message]" - 모든 업데이트가 성공하면 빈 배열을 반환합니다.
- 실패한 각 업데이트에 대한 오류 메시지의
string[]으로 반환하려면 List<string> errors = new List<string>();를 사용하세요. List<string>은 크기를 조정할 수 있는 배열처럼 작동하며, errors.Add(...)를 호출하여 항목을 추가할 수 있습니다. 마지막에는 errors.ToArray()로 변환하세요. 이를 위해 필요한 using System.Collections.Generic; 가져오기는 이미 파일 상단에 포함되어 있습니다.직접 해보기
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)
{
// 여기에 코드를 작성하세요
}
}
// 테스트에 필요함 - 수정하지 마세요
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)
{
// Check if student index is valid
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;
}
// Check if assignment index is valid
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 };
}
}논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러