Hi I have an assignment to do where I have to make a race between two cars (this assignment is a continuation of a previos 'mini' assignment where I had to do the 'race' with one car).
The commands that I implemented for the cars is foward (increases distance travelled), reverse (decreases the distance travelled), left and right (left and right doesn't increase or decrease the distance). Now what I need to do is make a race between two cars where what is currently displayed needs to be accompanied by the commands of the other car.
Console example of the layout.
To make the two columns you can use \t.
Car1. . . . . . . . . . . . . . . . .Car2
Forward 1km. (total). . . . . . Right.
Left. . . . . . . . . . . . . . . . . Reverse -1km. (total)
Forward 4km. (total). . . . . . Left.
Reverse 3km. (total). . . . . . Forward 3km. (total)
Oh and i'm using two classes because that is what was required by my lecturer.
Simulator.java
import java.util.Random; class Simulator{ public static void main(String args[]){ vehicleCMD car = new vehicleCMD(); Random rand = new Random(); int km, km_rev; int do_what; car.start(); while (car.cmd_start == true){ km = 1+rand.nextInt(3); km_rev = 1+rand.nextInt(1); do_what = rand.nextInt(4); switch(do_what) { case 0: km = car.forward(km); break; case 1: car.left(); break; case 2: car.right(); break; case 3: km_rev = car.reverse(km_rev); break; } if (car.total_km >= 70){ car.stop(); } } } }
Methods class.
public class vehicleCMD{ boolean cmd_start = false; boolean cmd_stop = false; boolean cmd_forward = false; boolean cmd_reverse = false; boolean cmd_right = false; boolean cmd_left = false; int total_km = 0; public void start(){ cmd_start = true; cmd_stop = false; System.out.println("Power ON."); } public void stop(){ cmd_stop = true; cmd_start = false; System.out.print("\n\nGas Tank empty. Car STALLED"); } public int forward(int km){ cmd_reverse = false; cmd_forward = true; total_km = total_km + km; System.out.println("Forward " +total_km+ "km. (total)"); return km; } public int reverse(int km_rev){ cmd_forward = false; cmd_reverse = true; total_km = total_km - km_rev; System.out.println("Reverse " +total_km+ "km. (total)"); return km_rev; } public void left(){ cmd_left = true; cmd_right = false; System.out.println("Left."); } public void right(){ cmd_right = true; cmd_left = false; System.out.println("Right."); } }
The code is in working order and is totally open source.