Know how many ports are open in Java program

Asked

Viewed 553 times

3

I have a program in Java to know how many doors are open but I’m not sure where to put the method to count the doors. I can create a method to count open doors within the class Porta?

    package programa2;
    public class Programa2 {
    public static void main(String[] args) {
    Porta minhaPorta1;
    minhaPorta1 = new Porta();
    minhaPorta1.dimensaoX = 100;
    minhaPorta1.dimensaoY = 80;
    minhaPorta1.dimensaoZ = 30;
    minhaPorta1.cor = null;
    minhaPorta1.pinta("Verde");
    System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
    minhaPorta1.abreFecha(1);

    Porta minhaPorta2;
    minhaPorta2 = new Porta();
    minhaPorta2.dimensaoX = 120;
    minhaPorta2.dimensaoY = 90;
    minhaPorta2.dimensaoZ = 40;
    minhaPorta2.cor = null;
    minhaPorta2.pinta("Azul");
    System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
    minhaPorta2.abreFecha(2);

    Porta minhaPorta3;
    minhaPorta3 = new Porta();
    minhaPorta3.dimensaoX = 70;
    minhaPorta3.dimensaoY = 60;
    minhaPorta3.dimensaoZ = 10;
    minhaPorta3.cor = null;
    minhaPorta3.pinta("Amarela");
    System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
    minhaPorta3.abreFecha(2);
}   
}

Porta Class:

package programa2;
public class Porta {

boolean aberta;
String cor;
int dimensaoX, dimensaoY, dimensaoZ;

void abre() {
    this.aberta = true;
}

void fecha() {
    this.aberta = false;
}

void pinta(String novaCor) {
    this.cor = novaCor;
}

void abreFecha(int respUsuario) {
    switch (respUsuario) {
        case 1:
            abre();
            System.out.println("A porta está aberta.\n");
        break;
        case 2:
            fecha();
            System.out.println("A porta está fechada.\n");
        break;
    }
} 
}

int quantasPortasEstaoAbertas(){
    int cont = 0;
    if(this.minhaPorta1.abreFecha(1)){              
        cont = cont + 1;
    }
    if(this.minhaPorta2.abreFecha(1)){
        cont = cont + 1;
    }
    if(this.minhaPorta3.abreFecha(1)){
        cont= cont + 1;
    }           
    return cont; 
}

2 answers

5


Introducing

You can always do what you want. Ideally, do what’s best for each situation. Those who are learning still don’t know what’s best. But it is certain that it is more advantageous to learn in steps. Start with the simple, so it solves. There is no point in learning all possible concepts and applying a valid technique without even knowing whether this technique is necessary or why you are using it. Worse, you can learn what is called "good practices", that is, someone tells you that right is such a thing and you go around repeating it without knowing why. And it happens a lot that in the name of doing the "good practice" often opts for a design more complex than it actually needs.

This is an exercise, the ideal is to learn all concepts correctly, but you do not need to learn concepts that are not absolutely necessary for this problem. Mainly you don’t need to learn concepts that are not unanimous.

Count the open doors

The class Porta should only take care of a door. But nothing prevents that it controls some general aspects of all existing doors. Again, whether this is the mistake or not for the problem does not know yet, and it becomes difficult to know since the problem is not real, it is only to train some aspects.

The easiest way to solve is to have a class variable (as opposed to an instance variable belonging to each object porta), so there is only one data for every application. In this variable you control how many are open. Of course, you have to add and subtract every time you open and close the door.

One can create a method to access this variable, as was done in the example. But as it will access a static variable (class) the method can be static as well.

Organizing the code

Taking advantage we will improve some things that already fit even in learning of simple thing. Get used to organize well the code. This is above average beginners, but some things can be improved.

Get used to saying the visibility of all members even if it is not necessary. Say what is public and what is private, this documents better. Especially make the variable aberta private. The ideal (but not always to be followed) is for all variables to be private. This particular one has no reason to go public since it is not publicly accessed.

Many people will say to create public access methods get and set for all variables and make them private. Depends, it might be good or not. Know you can do this, but understand first why to do it before you start applying.

Data on port dimensions seems to be mandatory, right? That is, if they don’t exist, the port doesn’t exist. If so, consider create a builder to send this data and only then the port can be created.

Small problems

I removed the lines that lay the cor as null. The creation of the class already guarantees this, is redundancy.

In the switch called the method abre() in both situations, I think this was a mistake. I fixed.

I took the this since he’s redundant, not everyone likes this.

I have my doubts if sending a number to a method open and choosing what to do is a good idea. It does not seem to be the responsibility of the class Porta take care of it, this method does not seem to be suitable there, but for an initial exercise is good so.

The day you think you need a more robust solution, which will use competition, if you have determined why you need to know how many doors are open, whether other general information about the doors will be necessary, whether they will be associated with something (a property, for example), that is, when you have a better defined problem, you can make a design more complex with other classes suitable for the problem. Without the proper definition of the requirements will create solutions Frankestein, That’s creating an addiction.

Completion

Obviously other improvements can be made, but I think it’s helped a lot.

In a real problem you will have to think of other things, this implementation is quite naive.

But I’d stay away from designs complex for now. Try to make the class on its own work well. When you’ve mastered it well, then you can think about architecture. Ideally with real problems.

class Porta {
    private static int portasAbertas = 0;
    private boolean aberta;
    public String cor;
    public int dimensaoX, dimensaoY, dimensaoZ;
    
    public void abre() {
        if (!aberta) {
            portasAbertas++;
            aberta = true;
        }
    }
    
    public void fecha() {
       if (aberta) {
            portasAbertas--;
           aberta = false;
       }
    }
    
    public void pinta(String novaCor) {
        cor = novaCor;
    }
    
    public void abreFecha(int respUsuario) {
        switch (respUsuario) {
            case 1:
                abre();
                System.out.println("A porta está aberta.\n");
            break;
            case 2:
                fecha();
                System.out.println("A porta está fechada.\n");
            break;
        }
    } 
    
    public static int quantasPortasEstaoAbertas() {
        return portasAbertas; 
    }
}

class Programa2 {
    public static void main(String[] args) {
        Porta minhaPorta1;
        minhaPorta1 = new Porta();
        minhaPorta1.dimensaoX = 100;
        minhaPorta1.dimensaoY = 80;
        minhaPorta1.dimensaoZ = 30;
        minhaPorta1.pinta("Verde");
        System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
        minhaPorta1.abreFecha(1);
    
        Porta minhaPorta2;
        minhaPorta2 = new Porta();
        minhaPorta2.dimensaoX = 120;
        minhaPorta2.dimensaoY = 90;
        minhaPorta2.dimensaoZ = 40;
        minhaPorta2.pinta("Azul");
        System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
        minhaPorta2.abreFecha(2);
    
        Porta minhaPorta3;
        minhaPorta3 = new Porta();
        minhaPorta3.dimensaoX = 70;
        minhaPorta3.dimensaoY = 60;
        minhaPorta3.dimensaoZ = 10;
        minhaPorta3.pinta("Amarela");
        System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
        minhaPorta3.abreFecha(2);
        
        System.out.println(Porta.quantasPortasEstaoAbertas());
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Wow, perfect! I know a basic PHP and I started two weeks studying java and object orientation for a workbook. I will observe the tips you gave and keep improving. Thank you very much.

3

The best place for this method is not within the class Porta, since, for this, you would need to pass a list of the instantiated doors for the count to be made. Note that ideally an instance of the port class should know only about it.

In this case, an alternative is to count this in a class called PortaManager. This class would have the list of instantiated ports in its application. A method would run through this list to return the number of doors that are open.

See the code below. The only change in the Main class is that ports need to be added in Portamanager.

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        PortaManager portaManager = new PortaManager();

        Porta minhaPorta1;
        minhaPorta1 = new Porta();
        minhaPorta1.dimensaoX = 100;
        minhaPorta1.dimensaoY = 80;
        minhaPorta1.dimensaoZ = 30;
        minhaPorta1.cor = null;
        minhaPorta1.pinta("Verde");
        System.out.println("A porta é: " + minhaPorta1.cor + " e as dimensões são " + minhaPorta1.dimensaoX + ", " + minhaPorta1.dimensaoY + ", " + minhaPorta1.dimensaoZ + ".");
        minhaPorta1.abreFecha(1);
        portaManager.adicionar(minhaPorta1);


        Porta minhaPorta2;
        minhaPorta2 = new Porta();
        minhaPorta2.dimensaoX = 120;
        minhaPorta2.dimensaoY = 90;
        minhaPorta2.dimensaoZ = 40;
        minhaPorta2.cor = null;
        minhaPorta2.pinta("Azul");
        System.out.println("A porta é: " + minhaPorta2.cor + " e as dimensões são " + minhaPorta2.dimensaoX + ", " + minhaPorta2.dimensaoY + ", " + minhaPorta2.dimensaoZ + ".");
        minhaPorta2.abreFecha(2);
        portaManager.adicionar(minhaPorta2);

        Porta minhaPorta3;
        minhaPorta3 = new Porta();
        minhaPorta3.dimensaoX = 70;
        minhaPorta3.dimensaoY = 60;
        minhaPorta3.dimensaoZ = 10;
        minhaPorta3.cor = null;
        minhaPorta3.pinta("Amarela");
        System.out.println("A porta é: " + minhaPorta3.cor + " e as dimensões são " + minhaPorta3.dimensaoX + ", " + minhaPorta3.dimensaoY + ", " + minhaPorta3.dimensaoZ + ".");
        minhaPorta3.abreFecha(2);
        portaManager.adicionar(minhaPorta3);

        System.out.println("A quantidade de portas abertas é: " + portaManager.quantasPortasEstaoAbertas());
    }
}

See the Portamanager class below. It can be improved, including methods for deleting ports, etc.

class PortaManager {
    private List<Porta> portas;

    PortaManager() {
        portas = new ArrayList<Porta>();
    }

    public int quantasPortasEstaoAbertas() {
        int resultado = 0;

        for (int i = 0; i < portas.size();i++) {
            if (portas.get(i).aberta)
                resultado++;
        }

        return resultado;
    }

    public void adicionar(Porta porta) {
        portas.add(porta);
    }
}
  • It would be right to put the method as much as Portsrates() in another class?

  • My proposal is exactly that, but for that, you need to know how to work with Java lists. Each instantiated port would be added in the Portamanager class (which will have a list of instantiated ports). This same class would have the How many Portslats method () that would go through the internal list in Portamanager and return how many are open.

  • I’m starting to study java now and still don’t know how to work with lists or arrays. Without this it is impossible to do with what is currently in the code?

  • It’s not impossible, but I wouldn’t go down that road, because it won’t add much to you, it can even create unnecessary addictions to your programming style. Arrays are basic programming structures, so learning them is critical. Note that the problem with how many doorsPortsSports() you wrote is that it only works for 3 doors and they need to call myPorta1,myPorta2,myPorta3.

  • Thanks friend, I will implement your solution in another example to use the best shape in each case.

Browser other questions tagged

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