Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

Me desafiando aprimorando o sistema de calculo de média.

Estava fazendo outra formação Java da Alura e acabei me deparando com esta de colocando em prática. Então, resolvi fazê-la, mesmo que sejam coisas bem simples, e ao mesmo tempo decidi me desafiar a melhorar e fazer implementações mais robustas do que as pedidas propriamente nos desafios. Este foi o resultado do desafio de calcular a média do aluno; usei alguns conhecimentos que obtive em outras formações e no que aprendi por mim mesmo.

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Assim está o código do desafio proposto. Sabendo que Java é supertipado, então resolvi dividir o código e suas devidas funções/métodos e atributos em seus respectivos objetos/classes.

Class Main

package org.maelys;

public class Main {
    public static void main(String[] args) {

        Student student = new Student();
        Notes notes = new Notes();

        student.setName("Eduardo");
        student.setAge(15);
        notes.appendAll(8.5, 4.5, 3.3, 5.6, 10.0);
        student.setNotes(notes);

        if (student.getNotes() == null) {
            System.out.println("No notes available for student");
            return;
        }

        double average = student.getNotes().average();
        if (average == -1) {
            System.out.println("No valid grades found for student");
            return;
        }

        student.printSummary(average);
    }
}

Class Student

package org.maelys;

@lombok.ToString(of = {"name", "age"})
@lombok.Getter(value = lombok.AccessLevel.PUBLIC)
@lombok.Setter(value = lombok.AccessLevel.PUBLIC)
@lombok.NoArgsConstructor(access = lombok.AccessLevel.PUBLIC)
public class Student {
    private String name;
    private int age;
    private Notes notes;

    public void printSummary(double average) {
        System.out.printf(
                "Student %s | Age: %d | Average grade: %.1f%n",
                getName(),
                getAge(),
                average
        );
    }
}

Class Notes

package org.maelys;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Represents a collection of grades, each of which must be within
 * the valid range of 0 to 10, inclusive. This class provides methods
 * for adding grades, accessing individual or all grades, and computing
 * the average of the grades.
 */
public class Notes {

    /* =========================== Fields =================================== */

    /** List that stores valid grades (between 0 and 10). */
    private final List<Double> notes = new ArrayList<>();

    /* ========================= Insert Methods ============================= */

    /**
     * Adds a single grade to the list if it is in the valid range (0 to 10).
     * Invalid values are ignored.
     *
     * @param note the grade to be added.
     */
    public void append(double note) {
        if (note < 0 || note > 10) return;
        this.notes.add(note);
    }

    /**
     * Adds multiple grades to the list. Each grade must be between 0 and 10.
     * Invalid values are ignored.
     *
     * @param note an array of grades to be added.
     */
    public void appendAll(double @NotNull ... note) {
        for (double d : note) {
            this.append(d);
        }
    }

    /* ========================= Read Methods =============================== */

    /**
     * Returns the grade at the given index, rounded to the nearest integer.
     * If the index is out of bounds, returns -1.
     *
     * @param index the position of the grade in the list.
     * @return the rounded grade, or -1 if the index is invalid.
     */
    @Contract(pure = true)
    public double getIndividualNote(int index) {
        if (index < 0 || index >= this.notes.size()) return -1;
        return Math.round(this.notes.get(index));
    }


    /**
     * Retrieves all grades in the collection.
     * The returned list is a copy of the internal list, ensuring
     * the original data remains unmodified.
     *
     * @return a list of all grades as Double values.
     */
    @Contract(pure = true)
    public List<Double> getAllNotes() {
        return new ArrayList<>(this.notes);
    }

    /**
     * Calculates the average of all grades in the list.
     * Returns -1 if the list is empty.
     *
     * @return the rounded average grade, or -1 if the list is empty.
     */
    @Contract(pure = true)
    public double average() {
        if (notes.isEmpty()) return -1;
        double sum = 0;
        for (Double note : notes) {
            sum += note;
        }
        return Math.round(sum / notes.size());
    }
}

Espero que ajude algum iniciante que venha a fazer este curso.

2 respostas
solução!

Olá, Rick, tudo bem?

Que legal que você está se desafiando a aprimorar o sistema de cálculo de média. Seu código está bem estruturado e modularizado, o que é ótimo para manutenção e escalabilidade. Continue assim! ✨

Uma dica interessante para o futuro é considerar o uso de uma estrutura de dados como o Map para associar diferentes disciplinas às notas, caso o sistema venha a crescer e precisar dessa flexibilidade. Veja este exemplo:

import java.util.HashMap;
import java.util.Map;

Map<String, Double> disciplinas = new HashMap<>();
disciplinas.put("Matemática", 9.0);
disciplinas.put("Português", 8.5);

disciplinas.forEach((disciplina, nota) -> System.out.printf("%s: %.2f%n", disciplina, nota));

Esse código cria um Map para armazenar notas de diferentes disciplinas e imprime essas notas. É uma maneira útil de organizar os dados de maneira eficiente.

Qualquer dúvida que surgir, compartilhe no fórum. Abraços e bons estudos!

Alura Conte com o apoio da comunidade Alura na sua jornada. Abraços e bons estudos!

Obrigado pela dica, vou praticar um pouco o uso do Map, confesso ter um pouco de dificuldade no seu uso. Bem, foi assim que ficou a class Disciplines com o uso dele:

package org.maelys.desafio03;

import java.util.HashMap;
import java.util.Map;

public class Disciplines {

    private final Map<String, Double> grades = new HashMap<>();

    /**
     * Adds a grade for a specific subject to the discipline.
     *
     * @param matter the name of the subject to which the grade belongs
     * @param grade the grade to be associated with the specified subject
     */
    public void addGrade(String matter, double grade) {
        this.grades.put(matter, grade);
    }

    /**
     * Prints all grades stored in the discipline along with their corresponding subjects.
     * Each grade is displayed in the format "subject: grade" with the grade rounded to two decimal places.
     * If no grades are present, the output will be empty.
     */
    public void printGrade() {
        for (Map.Entry<String, Double> entry : this.grades.entrySet()) {
            System.out.printf("%s: %.2f ", entry.getKey(), entry.getValue());
        }
    }

    /**
     * Calculates the average of all grades stored in the discipline.
     * If no grades are present, returns -1.
     *
     * @return the average of all grades, or -1 if no grades are available.
     */
    public double average() {
        return this.grades.values().stream().mapToDouble(Double::doubleValue).average().orElse(-1);
    }
}