Doubt regarding the Java two-dimensional array

Asked

Viewed 62 times

2

I have this two-dimensional array and wanted to create a different object for each of his entries, but I’m having trouble doing this with a for.

Scanner scanner = new Scanner(System.in);

Predio predio = new Predio();

Predio predioArray[][];

System.out.println("Digite a quantidade de Andares do Predio: ");
predio.setQtdAndares(scanner.nextInt());
System.out.println("Digite a quantidade de Apartamentos do Predio: ");
predio.setQtdApartamentos(scanner.nextInt());

predioArray = new Predio[predio.getQtdAndares()][predio.getQtdApartamentos()];

for(Predio[] auxPr: predioArray) {

}

Getting to that part I stopped, I don’t know how to do this for to initialize an object for each index of this two-dimensional array (i.e., it would do system.out for each Floor ( How many buildings on the floor? ) and for Each Apartment (How much room, kitchen, bathroom etc)).

  • Do you want to print all the floors and their rooms of all the buildings?? And where you are defining the rooms of each floor?

  • Your question is a little confused, try to improve a little on the issue of writing to make it easier

  • @Gustavo yes I still haven’t defined this in the class exactly because I’m having doubts in how I will initialize each object for each Intel, IE the Indice 0 would be the floor 0 ( esse andar 0, I will put a scanner for the user to define how many apartments will exist on this floor and so on) in case [andar] would be my Info.

  • @Andersonhenrique will try to modify, but basically I just wanted to initialize each object for each example: in a normal array, Agenda aux = new Agenda(), Agenda a[] = new Agenda[5] and then I would do a for: For(int i = 0 ; i<a.length; i++){ a[i] = new Agenda();}

  • 1

    @Joaospirit I understand. If a floor has no laundry, for example, your print could show something like: "laundry = 0" or when there is no it should not show?

  • @Gustavo might not even show it, I was able to do something like this but with this being normal within another being normal, but I couldn’t solve it by making one be enhanced :( .

  • 1

    Just make one inside another

Show 2 more comments

1 answer

2


Your modeling is kind of... weird. If the class Predio represents a building, an array of Predio actually represents several buildings (i.e., a street, a block, a condo, or something like that).

An array of something serves to represent several different instances of this thing. An array of buildings should not be used to represent a single building.

So forget what you’re doing and go back to your clipboard. If you want to represent the floors and apartments of the building, put this data inside a single building. And there are many different ways, depending on what you need to do.

An example would be to have a class to represent an apartment. There you could have an array of apartments within the class Predio:

public class Predio {
    private Apartamento[] aptos;
}

And the apartment could have the floor number, for example (or this could be inferred from the number - ex: apto 135 is on the thirteenth floor).

This is a simpler approach, since the apartments would all be in the same array and to know which ones are on a specific floor, would have to find the exact positions, either by making some calculation (if all floors have the same amount of apartments, the calculation is easier), either going through the array to find the apartments.

Of course it could also be:

private Apartamento[][] aptos;

Thus, the first index indicates the floor (aptos[0] is an array containing the ground floor apartments, aptos[1] is an array containing the first floor aptos, etc).

If you want to make it a little more complicated, you could have:

public class Andar {
    private Apartamentos[] aptos;
}

public class Predio {
    private Andar[] andares;
}

If the floor needs to have more information attached to it (I don’t know, there are buildings where there are no garbage cans on all floors, then this could be a class information Andar). But if the floor does not need to have any specific information, then it is not worth creating this class.


Another point is that you read the amount of floors and the amount total apartment building. So you’re assuming that all the floors have the same amount of apartments, and you just divide the total by the amount of floors? And if the user enters values that do not give an exact value?

Finally, an approach could be to use the array of apartments array, assuming that all floors have the same amount of apartments:

public class Predio {

    private Apartamento[][] aptos;

    public Predio(int qtdAndares, int aptosPorAndar) {
        this.aptos = new Apartamento[qtdAndares][aptosPorAndar];
    }

    public void adicionarApto(int andar, Apartamento apto) {
        if (andar >= this.aptos.length) {
            throw new IllegalArgumentException("O prédio só tem " + this.aptos.length + " andares");
        }
        // encontra a primeira posição não preenchida
        int i = 0;
        while (i < this.aptos[andar].length && this.aptos[andar][i] != null)
            i++;
        if (i >= this.aptos[andar].length) {
            throw new IllegalArgumentException("Andar " + andar + " já está com todos os apartamentos cadastrados");
        }
        this.aptos[andar][i] = apto;
    }
}

And to read the data:

Scanner scanner = new Scanner(System.in);
System.out.println("Digite a quantidade de Andares do Predio: ");
int qtdAndares = scanner.nextInt();
System.out.println("Digite a quantidade de Apartamentos por andar: ");
int aptosPorAndar = scanner.nextInt();
Predio predio = new Predio(qtdAndares, aptosPorAndar);
for (int andar = 0; andar < qtdAndares; andar++) {
    for (int apto = 0; apto < aptosPorAndar; apto++) {
        System.out.println("Digite o numero do apto");
        int numero = scanner.nextInt();
        // leia todos os dados que um apartamento precisa e passe todos para o construtor
        predio.adicionarApto(andar, new Apartamento(numero));
    }
}

Remember that in this case, the floor zero (ground floor) also counts. So if the user type 20 for the amount of floors, the building will have floors from 0 to 19.

In the example above I just read the apartment number and passed it to the builder, but in your case just modify this section to read all the data you need, and then create a constructor in the class Apartamento that already receives all this data (see more on "What good is a builder?")

To walk through the apartments of the building, it would be something like this:

for (Apartamento[] aptos : predio.getApartamentos()) {
    for (Apartamento apto : aptos) {
        System.out.println(apto.getNumero()); // acesse os demais dados do apto
    }
}
  • mt thanks bro !!!

  • In the case that adding Pto will allow only to be added the same number of floors to the apartment Qtd would be that?

  • 1

    @Joaospirit In this code I assumed the premise that all floors have the same amount of apartments. If you want each floor to have a different amount, you will have to read the amounts floor by floor.

  • Would you help me with one more question? I am thinking of a way of not needing the user to put the number of each apartment and yes go adding automatically ex: it would define a number ex: 100, and then the quantity, and then the position 0 would be 100, the position 1 would be 101 is possible?

  • 1

    @Joaospirit Yes, I could do something like int numero = andar * 100 + apto (instead of numero = scanner.nextInt()). So on the first floor you would have 100, 101, 102, on the second floor 200, 201, 202, etc.

  • mt thanks bro, I tried to print it using a sysout but I got this result: Predio [name=null, aptos=[[Lmodel.Apartment;@7ba4f24f, [Lmodel.Apartment;@3b9a45b3]], even though I did a to string in the predicate model and apt.

  • 1

    @Joaospirit aptos is an array, so either you go through it with for and prints one apartment at a time (like the example you have in the answer), or you can do Arrays.deepToString(aptos) (remembering that the class Apartamento must have its own method toString() also).

  • 1

    Another tip is: if you have more specific questions, even if related, maybe be the case to ask another question (but do a search on the site before, to see if there is something similar already). Is that new questions are visible to all users on the main page (which increases the chances of an answer), already here in the comments less people will see (and as soon as I turn off, decreases your chances of having an answer) :-)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.