Problem finding a solution in an array / list

Asked

Viewed 84 times

1

I’m having a problem printing data from an array.

I have 2 classes (Apartamento and Predio).

Within my class Predio i have a method that adds my apartment to a floor:

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 I’m having trouble thinking about how I could create a list or an array to extract data to print

Class Apartamento:

package model;

public class Apartamento {
    private Integer qtdQuarto, qtdBanheiro, qtdCozinha, qtdSala, numeroApt;

    public Apartamento() {
    }

    public Apartamento(Integer numeroApt) {
        this.numeroApt = numeroApt;
    }

    public Apartamento(Integer qtdQuarto, Integer qtdBanheiro, Integer qtdCozinha, Integer qtdSala, Integer numeroApt) {
        this.qtdQuarto = qtdQuarto;
        this.qtdBanheiro = qtdBanheiro;
        this.qtdCozinha = qtdCozinha;
        this.qtdSala = qtdSala;
        this.numeroApt = numeroApt;
    }

    public Integer getNumeroApt() {
        return numeroApt;
    }

    public void setNumeroApt(Integer numeroApt) {
        this.numeroApt = numeroApt;
    }

    public Integer getQtdQuarto() {
        return qtdQuarto;
    }

    public void setQtdQuarto(Integer qtdQuarto) {
        this.qtdQuarto = qtdQuarto;
    }

    public Integer getQtdBanheiro() {
        return qtdBanheiro;
    }

    public void setQtdBanheiro(Integer qtdBanheiro) {
        this.qtdBanheiro = qtdBanheiro;
    }

    public Integer getQtdCozinha() {
        return qtdCozinha;
    }

    public void setQtdCozinha(Integer qtdCozinha) {
        this.qtdCozinha = qtdCozinha;
    }

    public Integer getQtdSala() {
        return qtdSala;
    }

    public void setQtdSala(Integer qtdSala) {
        this.qtdSala = qtdSala;
    }

    @Override
    public String toString() {
        return "Apartamento [qtdQuarto=" + qtdQuarto + ", qtdBanheiro=" + qtdBanheiro + ", qtdCozinha=" + qtdCozinha
                + ", qtdSala=" + qtdSala + "]";
    }


}

Class Predio:

package model;

import java.util.Arrays;

public class Predio {
    private String nome;

    private Apartamento[][] aptos;

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

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

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }

    public Apartamento[][] getAptos() {
        return aptos;
    }

    public void setAptos(Apartamento[][] aptos) {
        this.aptos = aptos;
    }

    public void imprimirDadosPredio() {

    }

}

And mine main:

public class app {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Digite o nome do Predio: ");
        String nomePredio = scanner.next();

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

        System.out.println("Digite o prefixo de numeração dos Apartamentos: ");
        int prefApt = scanner.nextInt();

        Predio predio = new Predio(qtdAndares, aptosPorAndar,nomePredio);

        Apartamento apartamento = new Apartamento();

        for (int andar = 0; andar < qtdAndares; andar++) {
            for (int apto = 0; apto < aptosPorAndar; apto++) {
                int numero = andar * prefApt + apto;
                System.out.println("Digite a qtd de Quartos do apartamento "+numero+": ");
                int qtdQuartos = scanner.nextInt();
                System.out.println("Digite a qtd de Banheiros do apartamento "+numero+": ");
                int qtdBanheiros = scanner.nextInt();
                System.out.println("Digite a qtd de Cozinhas do apartamento "+numero+": ");
                int qtdCozinha = scanner.nextInt();
                System.out.println("Digite a qtd de Salas do apartamento "+numero+": ");
                int qtdSala = scanner.nextInt();

                predio.adicionarApto(andar, new Apartamento(qtdQuartos,qtdBanheiros,qtdCozinha,qtdSala,numero));
            }
        }

    }

}

In my main I create my building, I name it and some parameters like: qtdAndares, aptosPorAndar.

And in the builder of my class Predio (i have a composition, I have a two-dimensional array of apt in my class Predio):

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

And then I use one for to add my apartment to my index (Floor), with all apartment information, but after that I have a problem in how to create a list or how to pass an array as parameter to a method I will do to print the data, because in my main i only have an object and not an array.

1 answer

1


If you want to print out the apartment data of the building, you can do this directly on main, since the class Predio has a getter to get the apartments:

// dentro do main
for (Apartamento[] andar : predio.getAptos()) {
    for (Apartamento apto : andar) {
        System.out.println("Apto " + apto.getNumeroApt() + " tem " + apto.getQtdBanheiro() + " banheiro(s)");
        // imprima os dados do apto da maneira que achar melhor
    }
}

Evidently, predio.getAptos() (or the very predio) could be passed to another method (possibly from another class that knows how to print), and this method would do the for likewise:

public class OutraClasseQueSabeImprimirAptos {
    public void imprime(Predio predio) {
        for (Apartamento[] andar : predio.getAptos()) {
            for (Apartamento apto : andar) {
                System.out.println("Apto " + apto.getNumeroApt() + " tem " + apto.getQtdBanheiro() + " banheiro(s)");
                // imprima os dados do apto da maneira que achar melhor
            }
        }    
    }    
}

And in the main you would call this method, passing the building as parameter.


getters and setters

It is not something directly related to the problem, but the class Apartamento has setters that may not make sense. Once an apartment is created, the amount of rooms, kitchens and bathrooms can change? Maybe may, if the resident can break down walls and do renovations, but anyway, it doesn’t seem to make much sense to have a Setter for these data.

Same goes for the class Predio. Once a building is created, can it change its name? (maybe, then setNome can even make sense depending on the context and requirements of the system). But can it change the amount of floors and apartments? Maybe the method setAptos doesn’t make so much sense.

That’s just to make you think a little and not create getters and setters for everything automatically. Only create what makes sense. Read more about it here.


Another detail is that in class Apartamento the number is stored in the field numeroApt. But if he’s part of an apartment, it’s kind of "obvious" that he refers to the apartment number, so he could just call himself numero.

  • 1

    I think the right one is the third. Of course, it is always possible to define the problem in a way that the first options are correct, but in almost all real cases, and not just an exercise will not be correct. And if you’re going to exercise then you’d better do it the right way for the real case because exercising wrong helps get used to doing wrong. An object should not know where something will be printed, no matter if it is console, GUI , web, API, etc. The class has more than one responsibility and is not cohesive when it has something printed by itself. It’s not the end of the world but it’s wrong.

  • 2

    I find it curious that people want object-oriented programming that has brought much more confusion than procedural programming, before you didn’t have to think about it, now you do, and then there are people who will always wonder if you should do it like this, because having separate printing for some is not OOP, for others it is not SOLID or at least SRP, both hurt some principles that only happen by using OOP. If you’re gonna do OOP then do it right.

  • 1

    @Maniero You’re right, I removed the other options from the answer...

  • 2

    They’re even options, I just don’t think they’re the primaries, it’s that thing, if you’re doing something simple just to make it work and the design not important so ok, is that I find it strange that people use a language that sells as OOP (now stopped a little but loved to talk that it was only OOP) and not do following good precepts design, though they may be questioned in something simple. Not to mention that some people say that putting everything together to the object is good OOP (I think it is not, and many people also).

  • Opa vlw personal, a doubt: that my method that adds the apartment to the floor in the class predio I would be putting a "duty that is not of the class predio" or I am mistaken? In case would this method in a controller? Hehe I’m thinking about how to get this method out of this class, but I’m getting a little confused.

  • 1

    @hkotsubo and vlw by attention !!

  • 1

    @Joaospirit In this case I find it an exaggeration to put the method adicionarApto in another class, since a building "knows" how to organize its floors and the fittings of each floor.

  • @hkotsubo opa mano Could you ask me just one question? I have tried in every way to take the current value of my Dice (Floor), to print ex: for (Apartment[] floor : predio.getAptos()) { for (Apartment suitable : floor) { System.out.println("Apartment " + fit.getNumerApt() +" has " + fit.getQtdBathroom() + " bathroom(s)"+ fit.getQtdCozie() + kitchen(s)"+ fit.getQtdQuarto() + room(s)"+ fit.getQtdSala() + room(s)" // print the apto data the way you think best } }

  • 1

    @Joaospirit Using this syntax of the for, you can’t get the index, you can only do what is traditional: see here - although I could also catch the walk dividing the number of the apartment by 100 (but I think it’s easier to do what is normal)

Show 4 more comments

Browser other questions tagged

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