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);   
   }
}

    


3
  • 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. Commented Sep 13, 2020 at 15:34
  • As an aside: Do not compare Strings with == Commented Sep 13, 2020 at 15:34
  • thank you very much. Setting the variables to public fixed. Changed all of the == to equals() too Commented Sep 19, 2020 at 16:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.