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.
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.