Menu
Coddy logo textTech

Obsługa błędów

Część sekcji Logika i sterowanie przepływem ścieżki C# w Coddy. Lekcja 45 z 66.

challenge icon

Wyzwanie

Łatwy

Ulepszmy nasz system, dodając solidną obsługę błędów, która pozwoli sprawnie radzić sobie z potencjalnymi problemami. Utwórz klasę o nazwie ErrorHandler z następującymi metodami:

  1. ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex): Sprawdza poprawność indeksów wejściowych i zwraca odpowiedni komunikat o błędzie lub pusty ciąg, jeśli są poprawne.
    • Zwraca "Invalid student index", jeśli indeks ucznia wykracza poza zakres.
    • Zwraca "Invalid assignment index", jeśli indeks zadania wykracza poza zakres.
    • Zwraca pusty ciąg "", jeśli oba indeksy są poprawne.
  2. SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex): Bezpiecznie pobiera wynik z obsługą błędów.
    • Zwraca wynik, jeśli oba indeksy są poprawne.
    • Zwraca -999, jeśli którykolwiek indeks jest niepoprawny.
  3. ProcessBatchUpdate(int[][] scoreGrid, int[][] updates): Przetwarza aktualizacje zbiorcze, w których każda aktualizacja ma postać [studentIndex, assignmentIndex, score].
    • Zwraca tablicę string[] zawierającą komunikaty o błędach dla każdej nieudanej aktualizacji.
    • Każda aktualizacja może zakończyć się jednym z następujących komunikatów o błędzie:
      • "Invalid update format", jeśli aktualizacja nie zawiera dokładnie 3 wartości.
      • "Invalid student index": jeśli indeks ucznia wykracza poza zakres.
      • "Invalid assignment index": jeśli indeks zadania wykracza poza zakres.
      • "Invalid score value": jeśli wynik jest poza prawidłowym zakresem (0-100).
    • Formatuj każdy błąd w następujący sposób: "Error at index X: [specific error message]"
    • Zwróć pustą tablicę, jeśli wszystkie aktualizacje zakończą się powodzeniem.
Podpowiedź: Aby dynamicznie gromadzić błędy przed zwróceniem ich jako string[], użyj List<string> errors = new List<string>();. List<string> działa jak tablica o zmiennym rozmiarze, do której możesz dodawać elementy za pomocą errors.Add(...). Na końcu przekonwertuj ją za pomocą errors.ToArray(). Import using System.Collections.Generic; potrzebny do tego rozwiązania jest już umieszczony na początku pliku.

Spróbuj swoich sił

using System; // Nie usuwaj tej linii
using System.Collections.Generic;

public class ErrorHandler
{
    public static string ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // Wpisz tutaj swój kod
        
    }
    
    public static int SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // Wpisz tutaj swój kod
        
    }
    
    public static string[] ProcessBatchUpdate(int[][] scoreGrid, int[][] updates)
    {
        // Wpisz tutaj swój kod
        
    }
}

// Wymagane do testowania – nie modyfikuj
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)
    {
        // Sprawdź, czy indeksy nie wykraczają poza zakres
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length || 
            assignmentIndex < 0 || assignmentIndex >= scoreGrid[studentIndex].Length)
        {
            return -1;
        }
        
        // Sprawdź poprawność oceny
        if (!DataCollector.ValidateScore(score))
        {
            return -2;
        }
        
        // Ustaw ocenę
        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)
    {
        // Sprawdź, czy indeks ucznia jest prawidłowy
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // Oblicz sumę prawidłowych ocen
        for (int j = 0; j < scoreGrid[studentIndex].Length; j++)
        {
            int score = scoreGrid[studentIndex][j];
            if (score != -1)  // Pomiń nieocenione zadania
            {
                sum += score;
                count++;
            }
        }
        
        // Zwróć średnią lub 0, jeśli nie ma prawidłowych ocen
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static double CalculateAssignmentAverage(int[][] scoreGrid, int assignmentIndex)
    {
        // Sprawdź, czy są jacyś uczniowie
        if (scoreGrid.Length == 0)
        {
            return -1;
        }
        
        // Sprawdź, czy indeks zadania jest prawidłowy
        if (assignmentIndex < 0 || assignmentIndex >= scoreGrid[0].Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // Oblicz sumę poprawnych ocen za zadanie
        for (int i = 0; i < scoreGrid.Length; i++)
        {
            if (assignmentIndex < scoreGrid[i].Length)
            {
                int score = scoreGrid[i][assignmentIndex];
                if (score != -1)  // Pomiń nieocenione zadania
                {
                    sum += score;
                    count++;
                }
            }
        }
        
        // Zwróć średnią lub 0, jeśli nie ma prawidłowych ocen
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static int[] FindHighestScore(int[][] scoreGrid)
    {
        int highestStudentIndex = 0;
        int highestAssignmentIndex = 0;
        int highestScore = -1;
        
        // Znajdź najwyższą ocenę
        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 };
    }
}

Wszystkie lekcje w sekcji Logika i sterowanie przepływem

Poćwicz samodzielnie: Kompilator C# online