我真的在努力学习这个生成随机数并更新观察者类的类。如何找到所有这些随机数的平均值? (observation_avg)并将它们传递给观察员
A级
public abstract class A implements Observer {
public abstract String disp();
public abstract void update(Observable subject, Object o);
}
B级
public class B extends A {
public double limit;
public B(double limit) {
this.limit = limit;
}
public void update(Observable o, Object arg) {
if (observations_avg >= limit) {
System.out.println(disp());
}
}
public String disp() {
// observations_avg = sum of all observation, and divide it by the quantity of them
String d = "WARNING avg exceeded limit: " + observations_avg;
return d;
}
}
C班
public class C extends A {
Avg avg = new Avg(10);
public void update(Observable subject, Object o) {
System.out.println(disp());
}
public String disp() {
String d = "avg is " observations_avg+ ; // i want to display the average of all the random numbers
return d;
}
}
生成随机数并更新观察者类Avg
public class Avg extends Observable {
private int seed;
Random random = new Random();
public Avg(int seed) {
this.seed = seed;
random.setSeed(this.seed);
}
public double getRandom() {
double r = random.nextDouble()*10;
return r;
}
public void read() {
setChanged();
notifyObservers();
}
}
主要
public class Main {
public static void main(String[] args) {
Avg avg = new Avg(10);
// create observers and add them
B B_obj = new B(8);
C C_obj = new C();
avg.addObserver(B_obj);
avg.addObserver(C_obj);
try {
while (true) {
avg.read();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
提前谢谢。
答案 0 :(得分:0)
您需要在Avg对象中创建类似getAverage()的方法,然后在观察avg时检索该值:
public void update(Observable o, Object arg) {
Avg avg = (Avg) o;
double observations_avg = avg.getAverage();
if (observations_avg >= limit) {
System.out.println(disp());
}
}