Code:
class boatprogram5{
static int numboats=4;
static boatclass boat[]=new boatclass[numboats+1];
public static void main(String[]args){
boatclass boat0=new sailboatclass(1.6,0.3,1.1,10.4,35,false,65);
boat[1]=boat0;
boat0=new motorboatclass(30.5,10.8,-5.2,-1.4,18,25);
boat[2]=boat0;
boat0=new sailboatclass(3.8,2.4,7.2,-4.9,30,true,120);
boat[3]=boat0;
boat0=new motorboatclass(7.4,14.8,0.2,8.6,12,16);
boat[4]=boat0;
double time=0;
double deltatime=2.0;
while(time<=10.0){
System.out.println("Time: "+cpj.nf(time,7,2));
for(int i=1;i<=numboats;i++){
double nearestdistance=Double.MAX_VALUE;
for(int j=1;j<=numboats;j++){
if(i!=j){
if(boat[i].distance(boat[j])<nearestdistance){
nearestdistance=boat[i].distance(boat[j]);
boat[i].nearestboat=boat[j];
}
}
}
System.out.println("Boat "+i+" is at "+boat[i].positionstring());
System.out.println(" nearest boat is at "+boat[i].nearestboat.positionstring());
System.out.print(" distance: "+cpj.nf(boat[i].nearestdistance(),7,2));
String nearestboattype="";
if(boat[i].nearestboat instanceof sailboatclass)
{nearestboattype=" Sailboat";}
if(boat[i].nearestboat instanceof motorboatclass)
{nearestboattype=" Motorboat";}
System.out.println(" type="+nearestboattype);
}
time+=deltatime;
for(int i=1;i<=numboats;i++){
boat[i].moveboat(deltatime);
}
}
}
}
abstract class boatclass{
double x=0;
double y=0;
double vx=0;
double vy=0;
boatclass nearestboat;
public boatclass(double x,double y,double vx,double vy){
this.x=x; this.y=y;
this.vx=vx; this.vy=vy;
}
void moveboat(double deltatime){
x+=deltatime*vx;
y+=deltatime*vy;
}
void stop(){
vy=0;
vx=0;
}
double distance(boatclass otherboat){
double z=Math.sqrt(Math.pow((x-otherboat.x),2)+Math.pow((y-otherboat.y),2));
return z;
}
double nearestdistance() {
if(distance(nearestboat)<=3){
stop();
System.out.println(" Boat has stopped stopped");
}
return distance(nearestboat);
}
String positionstring(){
return("x ="+cpj.nf(x,7,2)+" y ="+cpj.nf(y,7,2));
}
}
class sailboatclass extends boatclass{
private int mastheight=0;
boolean sailsfurled=false;
double saildirection=0;
public sailboatclass(double x,double y,double vx,double vy, int mastheight, boolean sailsfurled,double saildirection){
super(x,y,vx,vy);
this.mastheight=mastheight;
this.sailsfurled=sailsfurled;
this.saildirection=saildirection;
}
}
class motorboatclass extends boatclass{
double fuellevel=0;
private double fueltanksize=0;
public motorboatclass(double x,double y,double vx,double vy,double fuellevel,double fueltanksize){
super(x,y,vx,vy);
this.fuellevel=fuellevel;
this.fueltanksize=fueltanksize;
}
}
Thanks in advance.
Bookmarks