Passing variable to another class Java

Orihime_Orion :

I need to pass the boolean value processed in class Buffer to class Reader. The following are the classes:

public class Buffer {

    public int read(int j) {
      (if condition) {
         setBool(true);
      }
      (else if condition) {
         setBool(false);
      }
       else
         setBool(true);
       return 0;
    }

    public boolean setBool(boolean value) {
        boolean val = value;
        return val;
    }
}
public class Reader implements Runnable{
    Buffer buffer;

    public Reader(Buffer buffer){
        this.buffer = buffer;
    }

    public synchronized void run() {
        int j=0;
        int k=0;
        while (k!=18)
           buffer.read(j);
           j++;
           k++;
    }
}

I tried creating another method in the class Buffer which will be called by the class Reader as shown below,

public class Buffer {
   private static boolean value; 

   public int read(int j) { ..... }
   public boolean setBool(boolean value { ....} 

   public boolean getBool() {
      boolean val = setBool(value);
      return val;
   }
}

public class Reader {
    Buffer buffer;

    public Reader(Buffer buffer){...}

    public synchronized void run() {
        int j=0;
        int k=0;
        while (k!=18)
           buffer.read(j);
           j++;
           k++;
          boolean value = getBool();
    }
}

however when I displayed the value of method setBool to check it displays both true and false. I am unsure as to how I should proceed.

azro :
  • You may use value as an attribute of Buffer, you'll have it's setter and getter,
  • also it seems that putting the second condition as first, allow you to remove one branch
  • also you need to return an int from read(j) actually it returns nothing
class Buffer {
    private boolean value;

    public int read(int j) {
        if (condition2) {
            this.value = false;
        } else {
            this.value = true;
        }
        return 0; 
    }

    public boolean isValue() {
        return value;
    }

    public void setValue(boolean value) {
        this.value = value;
    }
}

And so

class Reader implements Runnable {
    Buffer buffer;

    public Reader(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public synchronized void run() {
        int j = 0;
        int k = 0;
        while (k != 18) {
            buffer.read(j);
            j++;
            k++;
            boolean v = buffer.isValue();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=318026&siteId=1