Good I have an exercise carried out where I introduce a series of data of students and I keep them in an arraylist. What I want is to save in another arraylist only the students whose average grade is greater than or equal to 5 but I do not know how to start
Here the code:
public class Principal
{
public static void main(String[] args)
{
System.out.println("EJERCICIO ARRAYLIST EN JAVA\n");
Scanner tecla = new Scanner (System.in);
ArrayList <Alumnos> ArrayListAlumnos = new ArrayList();
Alumnos objAlumnos = new Alumnos();
Fecha objFecha = new Fecha();
//Introducimos datos
for(int i=0;i<2;i++)
{
objAlumnos = new Alumnos();
objFecha = new Fecha();
int notas[] = new int [3];
System.out.print("\nNumero de expediente del "+(i+1)+" alumno: ");
objAlumnos.setNumeroExpediente(tecla.nextInt());
tecla.nextLine();//Limpiar buffer
System.out.print("Dni: ");
objAlumnos.setDni(tecla.nextLine());
System.out.print("Nombre y apellidos: ");
objAlumnos.setNombre(tecla.nextLine());
System.out.println("Introduca fecha de nacimiento");
do{
System.out.print("Dia(1-31): ");
objFecha.setDia(tecla.nextInt());
System.out.print("Mes(1-12): ");
objFecha.setMes(tecla.nextInt());
System.out.print("Año(1980-1999): ");
objFecha.setAnio(tecla.nextInt());
if(objFecha.fechaCorrecta()==false)
{
System.out.println("\nFecha de nacimento incorrecta, introduzca de nuevo");
}
}while(objFecha.fechaCorrecta()==false);
tecla.nextLine();//Limpiar buffer
System.out.print("Curso: ");
objAlumnos.setCurso(tecla.nextLine());
System.out.println("\nIntroduzca notas correspondientes(1-10)");
for(int j=0;j<3;j++)
{
int nota;
do{
System.out.print("Nota "+(j+1)+" : ");
nota=tecla.nextInt();
if(nota<1 || nota>10)
{
System.out.println("\nLa notas deben ir del 1 al 10, introduzca de nuevo");
}
}while(nota<1 || nota>10);
notas[j]=nota;
}
System.out.println("La media de las notas es: " + calcularMedia(notas));
objAlumnos.setNotas(notas);
objAlumnos.setFecha_nacimiento(objFecha);
ArrayListAlumnos.add(objAlumnos);
}
//Visualizamos
System.out.println("\n\nDATOS INTRODUCIDOS\n");
for(int i=0;i<ArrayListAlumnos.size();i++)
{
objAlumnos = ArrayListAlumnos.get(i);
System.out.println(ArrayListAlumnos.get(i));
}
}
public static double calcularMedia(int[] notas)
{
double resultado = 0;
for(int nota: notas)
{
resultado+=nota;
}
return resultado/notas.length;
}
}
Another possibility, that does not require modifying your code, only an addition, is that when you have saved all the students, you go through the arrayList and store in another that you only believe those that meet your criteria, this can be done for example by creating A new method that receives an ArrayList as an argument, and runs through it to do what you require with the student objects inside.
Greetings.