Create a race between 3 cars in which they have different speed limits such as 20 mph, 60mph or 30. Respectively. the acceleration should be 15f/s or 10.23mph the race should be 3 tracks each of 1 mile long create instances for the 3 cars on the course and print out their speed, location and the time every 30 seconds
In java
Hi, please find the solution. I am incrementing the speed every second, according to the acceleration.
Feel free to make changes as required. Solution is working great.
public class Car { private float speedLimit; private float distanceTravelled=0; private float speed; public float getSpeedLimit() { return speedLimit; } public void addSpeed(float speed){ if(this.speed+speed>speedLimit) return;//cannot go beyond speed limit this.speed += speed; } public float getSpeed() { return speed; } /** * Makes the car travel with that speed */ public void travel(){ distanceTravelled+= speed; } public float getDistanceTravelled(){ return distanceTravelled; } public Car(float speedLimit) { this.speedLimit = speedLimit; } }
import java.time.LocalDateTime; public class Main { public static void main(String[] args) throws InterruptedException{ float acceleration = 10.23f/(60f*60f);//miles per sec, assuming acceleration is same for all /*the above speed gets added every second*/ Car a = new Car(20f/(60f*60f)); Car b = new Car(60/(60f*60f)); Car c = new Car(30/(60f*60f)); System.out.println("a's speed limit is "+a.getSpeedLimit()); System.out.println("B's speed limit is "+b.getSpeedLimit()); System.out.println("C's speed limit is "+c.getSpeedLimit()); LocalDateTime localDateTime = LocalDateTime.now(); int i = 0; while(true){ /*we need to add speed every second by acceleration amount*/ if(a.getDistanceTravelled()<1) a.addSpeed(acceleration); if(b.getDistanceTravelled()<1) b.addSpeed(acceleration); if(c.getDistanceTravelled()<1) c.addSpeed(acceleration); a.travel();b.travel();c.travel(); System.out.println("A Travelled "+a.getDistanceTravelled()+ " Distance & speed is "+a.getSpeed()); System.out.println("B Travelled "+b.getDistanceTravelled()+ " Distance & speed is "+b.getSpeed()); System.out.println("C Travelled "+c.getDistanceTravelled()+ " Distance & speed is "+c.getSpeed()); System.out.println(); System.out.println(); if(a.getDistanceTravelled()>1 && b.getDistanceTravelled()>1 && c.getDistanceTravelled()>1) break; Thread.sleep(1000);//wait for a sec before runnning again. } } }
A Travelled 0.10514166 Distance & speed is 0.0028416666 B Travelled 0.4972919 Distance & speed is 0.014208333 C Travelled 0.20744166 Distance & speed is 0.005683333 A Travelled 0.10798333 Distance & speed is 0.0028416666 B Travelled 0.51150024 Distance & speed is 0.014208333 C Travelled 0.21312499 Distance & speed is 0.005683333 A Travelled 0.110824995 Distance & speed is 0.0028416666 B Travelled 0.52570856 Distance & speed is 0.014208333 C Travelled 0.21880832 Distance & speed is 0.005683333
Get Answers For Free
Most questions answered within 1 hours.