[英]Assigning Random numbers to different Objects
I have a function that generates numbers randomly using Poisson's Distribution and I have a Bus class and a Bus Stop class as well.我有一个 function 使用泊松分布随机生成数字,我还有一个公共汽车 class 和一个公共汽车站 class 。 Now I have generated 5 bus objects and 15 bus stop objects.现在我已经生成了 5 个公共汽车对象和 15 个公共汽车站对象。 My goal here is to assign random numbers to these five bus objects to indicate their bus stop positions.我的目标是为这五个公共汽车对象分配随机数以指示它们的公共汽车站位置。
private static int getPoissonRandom(double mean){
Random r = new Random();
double L = Math.exp(-mean);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
Bus Stop Class巴士站 Class
public class busStop {
int bus_stop_id;
public busStop(){
this.bus_stop_id=bus_stop_id;
}
public void create_busStop(int total,int position){
for(int i=1; i<=total; i++){
bus_stop_id=i;
//System.out.println("Bus_Stop with ID:"+i+" Spawned");
setBusPosition(i,position);
}
}
public void setBusPosition(int bus_id, int stop_id){
System.out.println("Bus : "+bus_id+ " at Stop :"+stop_id);
}
}
Bus class总线class
public class Bus {
int capacity;
int bus_id=0;
public Bus(){
this.capacity=50;
this.bus_id=bus_id;
}
public void spawn_bus(int bus_total){
for(int i=1; i<=bus_total; i++){
bus_id=i;
System.out.println("Bus with ID:"+i+" created");
}
}
} }
Main Function主Function
public static void main(String[] args) {
int bus_number=5;
int total_bus_stops=15;
Bus bus = new Bus();
busStop stops = new busStop();
getPoissonRandom(5);
bus.spawn_bus(bus_number);
stops.create_busStop(total_bus_stops,getPoissonRandom(5));
}
when I run the code, I keep getting one number assigned to all 5 bus objects, but I want different random numbers using Poisson Distribution generator to be assigned to the 5 bus objects当我运行代码时,我不断将一个数字分配给所有 5 个总线对象,但我希望使用泊松分布生成器将不同的随机数分配给 5 个总线对象
you are facing this problem since you have called the random generation method once only.你正面临这个问题,因为你只调用了一次随机生成方法。 To achieve the desired output you need to call getPoissonRandom(double mean) inside create_busStopMethod something like that:要实现所需的 output 您需要在 create_busStopMethod 中调用 getPoissonRandom(double mean) ,如下所示:
public void create_busStop(int total,int position){
for(int i=1; i<=total; i++){
bus_stop_id=i;
//System.out.println("Bus_Stop with ID:"+i+" Spawned");
setBusPosition(i,MainClass.getPoissonRandom(position));
}
}
and then call the method as然后将该方法称为
stops.create_busStop(total_bus_stops,5);
or you can modify creat_busStop to accept id and position rather than total_bus_stops as follows:或者您可以修改 creat_busStop 以接受 id 和 position 而不是 total_bus_stops,如下所示:
public void create_busStop(int id,int position){
bus_stop_id=id;
setBusPosition(id,position);
}
} }
and then call the method within for loop as然后在 for 循环中调用该方法
for(int i=0;i<total_bus_stops;i++){
stops.create_busStop(i,getPoissonRandom(5));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.