Java - Problem with conditional

2

I have the following code:

   public class UnitatFamiliar extends Thread {

    Comandament comandament;

    public UnitatFamiliar(Comandament c) {
        comandament = c;

    }

    @Override
    public void run() {
        //Agafa el comandament
        comandament.agafa();
        int canal = (int) ((Math.random() * 5) + 1); //triem un canal al·leatoriament, entre el 1 i el 100

        Comandament CanalFinal = new Comandament();
        CanalFinal.setCanal(canal);

        if (canal == comandament.getCanal()) {
            comandament.setCanal(canal);
        } else {
            System.out.println(getName() + " està mirant el canal " + canal);
        }
        //Mira la tele
        try {
            Thread.sleep((long) (Math.random() * 350) + 300);  //utilitzem el mètode sleep per suspendre l'execució del Thread un temps aleatori de ms
        } catch (InterruptedException e) {
            System.out.println("Error!!!");
        }
        //Deixa el comandament
        comandament.deixa();
    }
}

I have something wrong and I do not know what it can be. The idea is:

  - Si el canal es diferente al canal que hay actualmente, muestra un mensaje.
  - Si es igual, entonces no hagas nada.

The problem is that it always shows the channel ... what am I wrong?

--- EDIT WITH THE PART OF CODE THAT IS MISSING:

    public class Comandament  {
   /*
    * Modifiqueu i afegiu el codi necessari per implementar la classe 
    * Comandament.
    */
    boolean avalible = true;
    int canal;

          public int getCanal()
        {
                return canal;
        }
        public void setCanal(int canal)
        {
                this.canal = canal;
        }

    synchronized void agafa() {

    while (avalible == false) {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }
    avalible = false;
    notify();
}

        synchronized void deixa() {
    avalible = true;
    notify();
}
    }
    
asked by Montse Mkd 08.03.2018 в 16:00
source

2 answers

1

Most likely the canal attribute should be a member of another class.

You have:

  • UnitatFamiliar extends Thread , which seems to be modeled by a person, a member of the family
  • Comandament , a share shared by all threads, apparently control of television

The channel that is currently being viewed should be an attribute of Comandament and not of UnitatFamiliar

So your comparison in this line:

if (canal != UnitatFamiliar.canal){ ... }

It should be something like:

if (canal != comandament.getCanal()){
    comandament.setCanal(canal);
    ...
}
    
answered by 13.03.2018 в 14:34
-1

Try to make an instance of your UnitatFamiliar since not instantiating it is not running the constructor and therefore your UnitatFamiliar.canal does not have an initial value.
Instances in this way unita = new UnitatFamiliar()

    
answered by 13.03.2018 в 15:26