0

I'm trying to get the function infoEst() to iterate over an array of objects and print out the object's name and location. It iterates fine but it seems like every index in the array is the exact same as the last entry.

Am I creating the array of objects incorrectly?

import java.util.Scanner;

public class Estudiante {
   static String nombre= "", promedio = "", pueblo = "", entrada = "";
   static int edad;
   static Estudiante[] objArray = new Estudiante[4];
   static Scanner input = new Scanner(System.in);
 
   Estudiante(String nom, int ed, String prom, String pueb) {
      this.nombre = nom;
      this.edad = ed;
      this.promedio = prom; 
      this.pueblo = pueb;
   }

   static void infoEst(String n) {
      for (int i = 0; i < objArray.length; i++) {
         if (objArray[i].nombre == n) {
            System.out.println(objArray[i].nombre + ", " + objArray[i].pueblo);
         }
      }
   }   

   public static void main(String[] args) {
      objArray[0] = new Estudiante("Joshua", 20, "A", "Aguadilla");
      objArray[1] = new Estudiante("Liliana", 21, "A", "Isabella");
      objArray[2] = new Estudiante("Cano", 27, "C", "Aguadilla");
      objArray[3] = new Estudiante("Eribelto", 22, "F", "Moca");
 
      
      // does not print anything when executed.    
      infoEst("Joshua"); 
      infoEst("Liliana");
      
      // the if statement block executes on index 0 so
      // it prints Eribelto, Moca 4 times.
      infoEst("Eribelto");
    
      // All of these print "Eribelto" which is last in the array
      System.out.println(objArray[0].nombre);
      System.out.println(objArray[1].nombre);
      System.out.println(objArray[2].nombre);
      System.out.println(objArray[3].nombre);   
   }
}

    


Jeremy
  • 1
  • Don't compare strings with `==`. Use `equals()` or `equalsIgnoreCase()`. It's not the cause of the problem (the cause is that your variables are `static`), but you still have to fix it because it will cause problems otherwise. – JustAnotherDeveloper Sep 13 '20 at 15:34
  • As an aside: [Do not compare `String`s with `==`](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Turing85 Sep 13 '20 at 15:34
  • thank you very much. Setting the variables to public fixed. Changed all of the == to equals() too – Jeremy Sep 19 '20 at 16:01

1 Answers1

1

It iterates fine but it seems like every index in the array is the exact same as the last entry.

static String nombre= "", promedio = "", pueblo = "", entrada = "";

Don't use static variables. This means each instance of the class shares the same information.

camickr
  • 321,443
  • 19
  • 166
  • 288