Menu
Coddy logo textTech

Error Handling

Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 45 из 66.

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; уже включен в начало файла.

Попробуйте сами

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 };
    }
}

Все уроки раздела Логика и управление потоком