Report Generation
Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 44 из 66.
Задание
СреднеТеперь, когда у нас есть система оценок, давайте создадим модуль отчетов для генерации форматированных отчетов об успеваемости студентов. Создайте класс под названием ReportGenerator с этими методами:
GenerateStudentReport(int[][] scoreGrid, int studentIndex): Возвращает форматированную строку с отчетом о баллах конкретного студента, среднем балле и буквенной оценке.- Формат: "Student #X | Average: YY.Y | Grade: Z\nAssignment scores: S1, S2, S3, ..." где S1, S2, S3, ... — это числовые баллы за каждое задание.
- Для невыполненных заданий (балл -1) отображайте "N/A" вместо балла.
- Возвращайте "Invalid student index" для любого недействительного индекса студента.
GenerateClassSummary(int[][] scoreGrid): Возвращает форматированную строку с обзором успеваемости класса.- Формат: "Class Summary\nTotal Students: X\nClass Average: YY.Y\nGrade Distribution: A: #, B: #, C: #, D: #, F: #"
GenerateAssignmentReport(int[][] scoreGrid, int assignmentIndex): Возвращает форматированную строку со статистикой для конкретного задания.- Формат: "Assignment #X | Average: YY.Y | Completion Rate: Z%"
- Процент выполнения — это процент студентов, у которых есть оценка за это задание (не -1).
- Возвращайте "Invalid assignment index" для любого недействительного индекса задания.
Попробуйте сами
using System; // Не удаляйте эту строку
using System.Text;
public class ReportGenerator
{
public static string GenerateStudentReport(int[][] scoreGrid, int studentIndex)
{
// Напишите ваш код здесь
}
public static string GenerateClassSummary(int[][] scoreGrid)
{
// Напишите ваш код здесь
}
public static string GenerateAssignmentReport(int[][] scoreGrid, int assignmentIndex)
{
// Напишите ваш код здесь
}
}
// 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 };
}
}
public class GradingSystem
{
public static string ConvertToLetterGrade(double score)
{
if (score < 0 || score > 100)
{
return "N/A";
}
else if (score >= 90)
{
return "A";
}
else if (score >= 80)
{
return "B";
}
else if (score >= 70)
{
return "C";
}
else if (score >= 60)
{
return "D";
}
else
{
return "F";
}
}
public static string GetStudentGrade(int[][] scoreGrid, int studentIndex)
{
double average = DataAnalyzer.CalculateStudentAverage(scoreGrid, studentIndex);
if (average == -1)
{
return "N/A";
}
return ConvertToLetterGrade(average);
}
public static int[] GetClassDistribution(int[][] scoreGrid)
{
int[] distribution = new int[5]; // [A, B, C, D, F]
for (int i = 0; i < scoreGrid.Length; i++)
{
string grade = GetStudentGrade(scoreGrid, i);
switch (grade)
{
case "A":
distribution[0]++;
break;
case "B":
distribution[1]++;
break;
case "C":
distribution[2]++;
break;
case "D":
distribution[3]++;
break;
case "F":
distribution[4]++;
break;
// Оценки N/A не учитываются в распределении
}
}
return distribution;
}
}Все уроки раздела Логика и управление потоком
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling8Data Analysis System
Data Collection SetupData Entry Logic3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety