PDA

View Full Version : Java Homework Help Needed



Elip007
01-22-2013, 05:02 PM
So I received this assignment from my Instructor and I am having a hard time wrapping my mind around it and getting it to work.
Not sure how much of you guys are willing to help, but I hope that some one can successfully code it so I could look at it and study it and see how it was done.

We are using Eclipse to code.


The Ford vs. Chevy car race


Our two cars begin the race at the starting gate “square 1” of 70 squares. Each square represents a
possible position along the race course. The finish line is at square 70. The first car to reach or pass
square 70 is the winner. There is a clock that ticks once per second and with each tick the computer
should adjust the position of the cars.


After each tick of the clock, display each car’s position on the course. The amount to move a car should
be determined by generating a random number between 1 and 10 and applying it as follows;


FOR FORD

If the number is between 1 and 5 move forward 3 spots.
If the number is between 6 and 8 move back 2 spots
If the number is 9 do nothing
If the number is 10 move forward 5 spots

FOR CHEVY

If the number is 1 move forward 5 spots
If the number is 2 do nothing
If the number is between 3 and 5 move back 2 spots
If the number is between 6 and 10 move forward 3 spots


For each tick of the clock (i.e. each repetition of the loop), print a 70 position line and show the position
of the Ford and Chevy cars by placing a F and C at their respective positions. Occasionally both cars will
be on the same space and when this happens you should print “2 car pileup”.


After printing each line, check to see if either car has reached or passed space 70. If this has happened,
terminate the program and print which car won.


Be sure to document your code with comments.

Again, if some one could do the coding for this successful, that would be great!
Thanks!

Recursive
01-22-2013, 05:57 PM
It is quite easy if you don't look to much at the timing part of the whole process and concentrate on the math aspect, then later implement timing.

I don't program in java, but the ideas in c/c++ can be easily transferred to java, so here is a way to look at it.
Create a struct that will represent each car. In the struct have:
Name of car
New position(1-70)
Displacement(New - 1)
Movement(use rand to determine this)

-In your main function, start the randomizer and make sure to specify 1 as floor and 10 as ceil.
-For each time it resets, use your conditions for each car to determine Movement.
-Call another function that will be printing the road and the position of each car
-Check displacement of each car and whichever one has highest Displacement is leading
-When their displacement is the same, you print car pileup
-While doing this, make sure their displacement is below 70!

Gl


E: Here it is in c++:


#include <iostream>
#include <cstdlib> //rand
#include <ctime> //srand

#define ZERO 1e-10
#define isBetween(A, B, C) ( ((A-B) > -ZERO) && ((A-C) < ZERO) )

bool DrawTrackAndDrivers(int, int* , int*, int* , int* );
int Distance(std::string, int);

struct Car
{
Car(std::string Name, int Pos, int Dist)
{
CarName = Name;
Position = Pos;
Distance = Dist;
}

~Car()
{
std::cout <<std::endl;
std::cout << CarName << " car deleted!\n";
}
std::string CarName;
int Position;
int Distance;
};

int main()
{
srand((unsigned)time(0));//Seed pseudo random number generator
Car Ford("Ford", 1, 0);
Car Chev("Chevy", 1, 0);

int Movement;

double checkTime = 0;

clock_t NewTime = clock();
clock_t PrevTime = NewTime;

while (1)
{
NewTime = clock();
checkTime += (double)(NewTime - PrevTime);
PrevTime = NewTime;

if (checkTime > (double)(CLOCKS_PER_SEC))//Multiply CLOCK_PER_SEC by how often you want race to update
{
std::cout << "\n\n\n";
//system("clear");//For linux/Mac users
//system("cls"); //For windows(I think)


Movement = rand() % 10 + 1;
if (DrawTrackAndDrivers(Movement, &Ford.Position, &Chev.Position, &Ford.Distance, &Chev.Distance))
{
std::cout << std::endl << Ford.CarName << " travelled a total of " << Ford.Distance << " meters!" <<std::endl;
std::cout << std::endl << Chev.CarName << " travelled a total of " << Chev.Distance << " meters!" <<std::endl;
break;
}
checkTime -= (double)(CLOCKS_PER_SEC);
}
}


return 0;
}

bool DrawTrackAndDrivers(int DistanceToMove, int *FPos, int *CPos, int *FDist, int *CDist)
{
bool pileup = false;

int FTravelledBy = Distance("Ford", DistanceToMove);
int CTravelledBy = Distance("Chevy", DistanceToMove);

if (FTravelledBy < 0)
*FDist += (-1 * FTravelledBy);
else
*FDist += FTravelledBy;

if (CTravelledBy < 0)
*CDist += (-1 * CTravelledBy);
else
*CDist += CTravelledBy;

*FPos += FTravelledBy;
*CPos += CTravelledBy;

if (*FPos >= 70)
{
std::cout << "Ford won the race!\n";
return true;
}
else if (*CPos >= 70)
{
std::cout << "Chevy won the race!\n";
return true;
}
else
for (int T = 0; T < 70; ++T)
{
std::cout << "=";
if (*FPos == *CPos && !pileup)
{
while (T < *FPos)
{
++T;
std::cout << "=";
}
pileup = true;
std::cout <<"2 car pileup ";
while(T < 70)
{
std::cout << "=";
++T;
}
continue;
}

else if (T+1 == *FPos)
std::cout << "ƒ ";
else if (T+1 == *CPos)
std::cout << "€ ";
}


return false;

}

int Distance(std::string Car, int MoveCar)
{
int Which;
int dist = 0;
if (Car == "Ford")
Which = 1;
else
Which = 2;

switch(Which)
{
case 1:
if (isBetween(MoveCar, 1, 5))
dist = 3;
else if (isBetween(MoveCar, 6, 8))
dist = -2;
else if (MoveCar == 10)
dist = 5;
break;

case 2:
if (isBetween(MoveCar, 3, 5))
dist = -2;
else if (isBetween(MoveCar, 6, 10))
dist = 3;
else if(MoveCar == 1)
dist = 5;
break;

default:
return dist;
break;

}
return dist;

}

Output:

./Race



====€ ================================================== ================


=======€ ================================================== =============


==========€ ================================================== ==========


==========€ ================================================== ==========


=============€ ================================================== =======


=ƒ ==========€ ================================================== =========


==============€ ================================================== ======


==ƒ ==========€ ================================================== ========


===============€ ================================================== =====


==================€ ================================================== ==


=====================€ =================================================


=====================€ =================================================


========================€ ==============================================


==ƒ =========================€ ===========================================


=====ƒ ====================€ =============================================


========ƒ =================€ =============================================


===========ƒ ============€ ===============================================


=========ƒ =================€ ============================================


============ƒ ===================€ =======================================


===============ƒ ==============€ =========================================


==================ƒ =========€ ===========================================


=====================ƒ ===========€ ======================================


========================ƒ ======€ ========================================


===========================ƒ =€ ==========================================


===============================€ =ƒ ======================================


==============================ƒ ====€ ====================================


==============================ƒ =======€ =================================


=================================ƒ ==€ ===================================


=================================€ ===ƒ ==================================


======================================€ =ƒ ===============================


==========================================ƒ =€ ===========================


========================================ƒ ======€ ========================


======================================ƒ ===========€ =====================


=========================================ƒ ======€ =======================


============================================ƒ ===€ =======================


=============================================€ ==ƒ =======================


=============================================ƒ ===€ ======================


==============================================€ ==ƒ ======================


==============================================€ =====ƒ ===================


================================================== 2 car pileup =====================


================================================== ==€ ==ƒ ================


================================================== ==ƒ ===€ ===============


================================================== ===€ ==ƒ ===============


================================================== ===ƒ ===€ ==============


================================================== ========ƒ =€ ===========


================================================== =======€ ====ƒ =========


================================================== =====€ =========ƒ ======


================================================== ========€ ====ƒ ========


================================================== ==========ƒ =€ =========


================================================== =========€ ====ƒ =======


================================================== ============€ ======ƒ ==


================================================== ===============€ =ƒ ====


================================================== ==============ƒ ====€ ==


================================================== ================€ =ƒ ===


================================================== =================ƒ ==€ =


Chevy won the race!

Ford travelled a total of 148 meters!

Chevy travelled a total of 143 meters!

Chevy car deleted!

Ford car deleted!

Elip007
01-22-2013, 11:20 PM
Wow [Re]cUrSivE, thanks for all that! I have been studying that and trying to convert it into Java. Some parts are a bit tricky, but isn't that bad overall.

I'd still love it for an actual Java version of it, but I'll try to work with that I have.

[XoL]
01-23-2013, 04:05 AM
You could try something like this (I didn't really read the assignment but from what I gathered, sorry in a rush)


import java.util.Scanner;

public class RaceTrack
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Car[] c = new Car[2];
c[0] = new Chevy();
c[1] = new Ford();

for(int i = 0; i < c.length; i++)
{

c[i].getReady();
}

for (int i = 0; i < 70; i++)
{
for(int j = 0; j < c.length; j++)
{
c[j].takeAStep();
}
System.out.println("------------------------------");
for(int j = 0; j < c.length; j++)
{
c[j].showPosition();
}
System.out.println("------------------------------");
for (int j = 0; j < 70; j++)
{
System.out.println();
}
keyboard.nextLine();
}
}
}

public class Car
{

int position; // 0 at the gate
int trackLength = 70;

void takeAStep()
{
if (position < trackLength)
{
position = position + 1; //this would be null because you simply overwrite with the other class that is the extendee (chevy/ford)
}
}

void showPosition()
{
// Print a little text picture
for (int i = 1; i <= position; i++)
{
System.out.print(" ");
}
System.out.print("c");
for (int i = 1; i <= trackLength - position - 1; i++)
{
System.out.print(" ");
}
if (position < trackLength)
{
System.out.print("|");
}
System.out.println();
}

void getReady()
{
position = 0;
}
}


public class Ford extends Car
{
void takeAStep()
{
if (position < trackLength)
{
int step;
double x = Math.random();
if (x >= 5)
{
step = 3;
}
else if (x >= 8)
{
step = -2;
}
else if (x = 9)
{
step = 0;
}
else
{
step = 5;
}
position += step;
}
}
}


I am assuming you can figure out how to do chevy with the ford one up there.
Again its pretty rough but generally should be the jist of what you asked for, don't really have a lot of time atm to finish it but im pretty confident you can finish this one up.

uhh ending note; my bad for not commenting I think the variable names are pretty self explanatory though.

Echo_
01-23-2013, 06:37 PM
I wrote this in about 15 minutes so it's a little messy.

Car.java
import java.util.Random;

public abstract class Car {
protected int position;
private static final Random random = new Random();

protected Car() {
position = 0;
}

protected int getPosition() {
return position;
}

protected static int getRandomNumber() {
return random.nextInt(9) + 1;
}

protected abstract void move();
}


Ford.java
public class Ford extends Car {
public Ford() {
super();
}

@Override
public void move() {
int i = getRandomNumber();
if (i >= 1 && i <= 5)
position += 3;
else if (i >= 6 && i <= 8)
position -= 2;
else if (i == 9)
return;
else if (i == 10)
position += 5;
}
}

Chevy.java
public class Chevy extends Car {
public Chevy() {
super();
}

@Override
public void move() {
int i = getRandomNumber();
if (i == 1)
position += 5;
else if (i == 2)
return;
else if (i >= 3 && i <= 5)
if ((position - 2) < 0)
position = 0;
else
position -= 2;
else if (i >= 6 && i <= 10)
position += 3;
}
}

Main.java
public class Main {
private static char[] defaultTrack = new char[70];
private static char[] track = new char[70];

private static boolean updateTrack(Ford ford, Chevy chevy) {
System.arraycopy(defaultTrack, 0, track, 0, track.length);
if (ford.getPosition() == chevy.getPosition()) {
System.out.println("2 car pileup");
return false;
}

if (ford.getPosition() > 69) {
System.out.println("The Ford won!");
return true;
} else if (chevy.getPosition() > 69) {
System.out.println("The Chevy won!");
return true;
}

if (ford.getPosition() < 0) {
track[0] = 'F';
} else {
track[ford.getPosition()] = 'F';
}

if (chevy.getPosition() < 0) {
track[0] = 'C';
} else {
track[chevy.getPosition()] = 'C';
}

System.out.println(track);
return false;
}

public static void main(String[] args) {
Ford ford = new Ford();
Chevy chevy = new Chevy();
updateTrack(ford, chevy);
while (!updateTrack(ford, chevy)) {
ford.move();
chevy.move();
}
}

static {
for (int i = 0; i < defaultTrack.length; i++)
defaultTrack[i] = ' ';
}
}

Elip007
01-23-2013, 06:49 PM
This is what I have came up so far. They both do the race and the winner gets chosen.
Now what I am stuck on is how do I draw out the race as the assignment asks? Not sure how I can take my Coding and make it be able to draw it all out as the race goes on..


public class Final_Project {


public static class Race {
/**
* Returns The Number Of Steps For Ford
*
* @param = Num ( A Random Step )
* @return = The Amount Of Steps
**/

private static int GetStepFord(int num) {
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
return 3;
case 6:
case 7:
case 8:
return -2;
case 9:
return 0;
case 10:
return 5;
}
return -1;
}

/**
* Retuns The Number Of Steps For Chevy
*
* @param = Num ( A Random Step )
* @return = The Amount Of Steps
*/
private static int GetStepChevy ( int num ) {
switch (num) {
case 1:
return 5;
case 2:
return 0;
case 3:
case 4:
case 5:
return -2;
case 6:
case 7:
case 8:
case 9:
case 10:
return 3;
}
return -1;
}


public static void main (String[] args) {
int posFord = 0;
int posChevy = 0;

Random rand = new Random();

while (true) {

//Calculates Next Random Value
int randFord = rand.nextInt(9) + 1;
int randChevy = rand.nextInt(9) + 1;

//Gets Next Amount Of Steps For Ford
int stepFord = GetStepFord ( randFord ) ;

//Checks
if ( stepFord == -1 ) {
System.out.println ("Error") ;
break ;
}

//Increments Position Of Ford
posFord += stepFord;

//Checks If Ford Has Won
if (posFord >=70) {
System.out.println("The Ford Has Won");
break ;
}

//Gets Next Amount Of Steps For Chevy
int stepChevy = GetStepChevy ( randChevy) ;

//Checks
if ( stepChevy == -1 ) {
System.out.println("Error");
break;
}

//Increments Position Of Chevy
posChevy += stepChevy;

//Checks If Chevy Has Won
if (posChevy >=70){
System.out.println("Chevy Has Won");
break;
}

System.out.println("Ford: " + posFord);
System.out.println("Chevy: " + posChevy);

//Tick Of Clock
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

}

Recursive
01-23-2013, 07:31 PM
@Elip007

Found this on stack overflow: (http://stackoverflow.com/questions/238920/how-do-i-calculate-the-elapsed-time-of-an-event-in-java)

long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();

System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");

You can use this and follow the method I used to run the events every second

Elip007
01-23-2013, 07:44 PM
cUrSivE;1162616']@Elip007

Found this on stack overflow: (http://stackoverflow.com/questions/238920/how-do-i-calculate-the-elapsed-time-of-an-event-in-java)

long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();

System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");

You can use this and follow the method I used to run the events every second

So your saying to use a clock to print out the race?
At the moment I receive

Ford: 19
Chevy: 66
Ford: 17
Chevy: 69
How would I turn that into something like you had, your output.

[XoL]
01-23-2013, 08:45 PM
You can follow what I wrote up there it will display a race albeit a bit of tweaking is needed as it is very rough and some pseudo code.

Elip007
01-23-2013, 09:28 PM
;1162645']You can follow what I wrote up there it will display a race albeit a bit of tweaking is needed as it is very rough and some pseudo code.

So your saying to screw around with your Racetrack code and try to implement that into my code?

[XoL]
01-23-2013, 09:51 PM
Basically I think I didn't read the first page correctly so I created two lanes so besides that it should be fine, and instead of two cars both cars are represented by a C so change that as well.

Recursive
01-24-2013, 12:41 AM
So your saying to use a clock to print out the race?
At the moment I receive

Ford: 19
Chevy: 66
Ford: 17
Chevy: 69
How would I turn that into something like you had, your output.


I have looked at your code and everyone else's here and none of it makes sense to me. Here is something else I found from oracle:

public class Timer
extends Object
implements Serializable
Fires one or more ActionEvents at specified intervals. An example use is an animation object that uses a Timer as the trigger for drawing its frames.

Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. For example, the following code creates and starts a timer that fires an action event once per second (as specified by the first argument to the Timer constructor). The second argument to the Timer constructor specifies a listener to receive the timer's action events.


int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
Timers are constructed by specifying both a delay parameter and an ActionListener... (http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html)

Where it says "perform a task", that is where I called the "DisplayTrackandDrivers()" function in my code to draw the track. The way I drew the track was to run a for loop that will print equal signs to output and as the for loop is going, I start checking at every (i+1 'equal sign' > 70) to see:

1. When their positions are the same
-If the position is the same, I use a while loop inside that condition to draw out equal signs until it is 1 less than the car's current position
-Then I print out the "2 car pileup" then still in the while, I finish printing out the track and continue

2.Who is leading and print a C or F on the track.

3. If someone won.
-If someone won, I return true in my function and the timer will stop because I will break out of the for-loop in main

Elip007
01-24-2013, 04:47 AM
cUrSivE;1162739']I have looked at your code and everyone else's here and none of it makes sense to me.

I am curious to why it doesn't make any sense to you. Is it because the coding is out of order or because you do C++?
Will give it a try to what you have said. I believe I am taking it all in the wrong way and it is causing me to screw up when I try to code it. I am missing something major, but don't know what it is.


;1162676']Basically I think I didn't read the first page correctly so I created two lanes so besides that it should be fine, and instead of two cars both cars are represented by a C so change that as well.

I don't seem to understand what you are trying to say here..

[XoL]
01-24-2013, 04:53 AM
In theory what I wrote (Cause I didn't test it) will look like this



--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

Ford Winner!

All you need to do is make it all one line and change the c's into F and C

Elip007
01-24-2013, 05:01 AM
;1162853']In theory what I wrote (Cause I didn't test it) will look like this



--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

--------------------------------------------
C
C
--------------------------------------------

Ford Winner!

All you need to do is make it all one line and change the c's into F and C

Oh I see. I tried to test your coding but have received multiple errors so I might have to change a few things around in it to make it work with mines.

How would I use my code and add your racetrack in? Would I just have to change the "c" or will it require more than just that?

Recursive
01-24-2013, 06:16 AM
I am curious to why it doesn't make any sense to you. Is it because the coding is out of order or because you do C++?

I don't code in java :s

Elip007
01-24-2013, 08:16 AM
cUrSivE;1162874']I don't code in java :s

Yeah that's what I thought. I'll look over though your C++. It's confusing to me but I think I can make out a few things here and there. Really would like to have this assignment finished and completed.

Brandon
01-25-2013, 06:44 PM
Yeah that's what I thought. I'll look over though your C++. It's confusing to me but I think I can make out a few things here and there. Really would like to have this assignment finished and completed.


Ahh for the C++ solutions of above, I think I read somewhere that CLOCKS_PER_SEC is inaccurate or something? :S I usually use std::chrono::high_resolution::now();
and std::chrono::duration..


IMO, Echo_ wrote the neatest code on the thread.. Here is another approach though.. Overriding toString().


Not sure if I understood the whole problem but this is how I approached what I thought was expected from your OP.

Class: Car

package carrace;

public class Car {
private String Symbol;
private int Position;

public Car(String CarSymbol) {
Position = 0;
Symbol = CarSymbol;
}

public void SetPosition(int Position) {
this.Position = Position;
}

public int GetPosition() {
return this.Position;
}

public void ResetPosition() {
Position = 0;
}

@Override public String toString() {

switch (Position) {
case 0: return String.format(Symbol + "%68s|", ".").replace(' ', '.');
case 69: return String.format("%" + String.valueOf(Position) + "s", Symbol).replace(' ', '.') + '|';
case 70: return String.format("%" + String.valueOf(Position) + "s", Symbol).replace(' ', '.');
default: return String.format("%" + String.valueOf(Position) + "s", Symbol).replace(' ', '.') + String.format("%" + String.valueOf(69 - Position) + "s|", ".").replace(' ', '.');
}
}
}




Class Ticker:

package carrace;

public class Ticker {
private java.util.Timer T;

public Ticker(final Car Ford, final Car Chevy) {
T = new java.util.Timer();

java.util.TimerTask Task = new java.util.TimerTask() {
@Override public void run() {
int RandomNumber = new java.util.Random().nextInt(10) + 1;

//FORD Section..

if (RandomNumber >= 1 && RandomNumber <= 5) {
Ford.SetPosition(Ford.GetPosition() + 3);
}
else if (RandomNumber >= 6 && RandomNumber <= 8) {
Ford.SetPosition(Ford.GetPosition() - 2);
}
else if (RandomNumber == 10) {
Ford.SetPosition(Ford.GetPosition() + 5);
}


//CHEVY Section..

if (RandomNumber == 1) {
Chevy.SetPosition(Chevy.GetPosition() + 5);
}
else if (RandomNumber >= 3 && RandomNumber <= 5) {
Chevy.SetPosition(Chevy.GetPosition() - 2);
}
else if (RandomNumber >= 6 && RandomNumber <= 10) {
Chevy.SetPosition(Chevy.GetPosition() + 3);
}


//BOTH Section..

if (Ford.GetPosition() == Chevy.GetPosition()) {
System.out.println("\n2 Car Pile-Up\n");
}
else {
System.out.println(Ford.toString());
System.out.println(Chevy.toString() + "\n");
}

if (Ford.GetPosition() >= 70) {
T.cancel();
System.out.println("Ford Is The Winner!");
}
else if (Chevy.GetPosition() >= 70) {
T.cancel();
System.out.println("Chevy Is The Winner!");
}
}
};

T.schedule(Task, 1000, 1000);
}
}



Main:

package carrace;

public class CarRace {
public static void main(String[] args) {
Car F = new Car("F");
Car C = new Car("C");

Ticker T = new Ticker(F, C);
}
}




It prints like:


.....F............................................ ...................|
..C............................................... ...................|

........F......................................... ...................|
C................................................. ...................|

...........F...................................... ...................|
C................................................. ...................|

..............F................................... ...................|
C................................................. ...................|

............F..................................... ...................|
.C................................................ ...................|

............F..................................... ...................|
....C............................................. ...................|

..........F....................................... ...................|
.......C.......................................... ...................|

.............F.................................... ...................|
.....C............................................ ...................|

................F................................. ...................|
..........C....................................... ...................|

...................F.............................. ...................|
........C......................................... ...................|

.................F................................ ...................|
...........C...................................... ...................|

....................F............................. ...................|
................C................................. ...................|

..................F............................... ...................|
...................C.............................. ...................|

.....................F............................ ...................|
........................C......................... ...................|

.....................F............................ ...................|
...........................C...................... ...................|

...................F.............................. ...................|
..............................C................... ...................|

......................F........................... ...................|
............................C..................... ...................|

.........................F........................ ...................|
..........................C....................... ...................|

............................F..................... ...................|
........................C......................... ...................|

............................F..................... ...................|
...........................C...................... ...................|

...............................F.................. ...................|
...........................C...................... ...................|

.............................F.................... ...................|
..............................C................... ...................|

................................F................. ...................|
..............................C................... ...................|

...................................F.............. ...................|
..............................C................... ...................|

......................................F........... ...................|
...................................C.............. ...................|

.........................................F........ ...................|
...................................C.............. ...................|

............................................F..... ...................|
.................................C................ ...................|

..........................................F....... ...................|
....................................C............. ...................|

.............................................F.... ...................|
.........................................C........ ...................|

................................................F. ...................|
.......................................C.......... ...................|

.................................................. .F.................|
.....................................C............ ...................|

.................................................. ....F..............|
...................................C.............. ...................|

.................................................. .......F...........|
.................................C................ ...................|

.................................................. ..........F........|
...............................C.................. ...................|

.................................................. ........F..........|
..................................C............... ...................|

.................................................. ...........F.......|
..................................C............... ...................|

.................................................. .........F.........|
.....................................C............ ...................|

.................................................. ............F......|
...................................C.............. ...................|

.................................................. .................F.|
......................................C........... ...................|

Ford Is The Winner!

Elip007
01-28-2013, 06:50 PM
Alright so after some time of trying to perfect it and make it work flawlessly, I have came up with the following for those who are interested.


import java.util.Random;

public static class Race {


/**
* Returns The Number Of Steps For Ford
*
* @param = Num ( A Random Value )
* @return = The Amount Of Steps
**/
private static int GetStepFord ( int num ) {
switch ( num ) {
case 1:
case 2:
case 3:
case 4:
case 5:
return 3;
case 6:

case 7:
case 8:
return -2;
case 9:
return 0;
case 10:
return 5;
}
return -1;
}


/**
* Retuns The Number Of Steps For Chevy
*
* @param = Num ( A Random Value )
* @return = The Amount Of Steps
**/
private static int GetStepChevy ( int num ) {
switch ( num ) {
case 1:
return 5;
case 2:
return 0;
case 3:
case 4:
case 5:
return -2;
case 6:
case 7:
case 8:
case 9:
case 10:
return 3;
}
return -1;
}



public static void main ( String[] args ) {
// Both Cars Start At Square 1
int posFord = 1;
int posChevy = 1;


Random rand = new Random();

while ( true ) {

int random = rand.nextInt(9) + 1;

//Gets The Step Value
int stepFord = GetStepFord ( random ) ;
int stepChevy = GetStepChevy ( random ) ;

//Will Add The New Step Value On To Its Position
posFord += stepFord;
posChevy += stepChevy;


System.out.print ("[");


/**
* If Both Cars End Up Being In The Same Position,
* It Will Print Out "Two Car Pile Up"
* Put The End Bracket
* Also At The End Of The Line, It will Print Out The Position Of Both Cars As Reference
**/
if ( posFord == posChevy ) {
System.out.print (" Two Car Pile Up ");
System.out.print ("]");
System.out.print ("\t\t\t\t\t\t\t Ford: " + posFord);
System.out.print (" Chevy: " + posChevy);
}
else {


/**
* The Main Loop For The Race Track And Race
* The Race Track Is 70 Spaces Long
* If i == The Position Of Ford, It Will Print A "F"
* If i == The Position Of Chevy, It Will Print A "C"
* For All The Other Spaces, It Will Print "-"
**/
for ( int i = 1; i <= 70; i++ ) {
if ( i == posFord )
System.out.print ("F");
else if ( i == posChevy )
System.out.print ("C");
else System.out.print ("-");
}
System.out.print ("]");


// Will Print Out The Actual Positions Of Both Cars For Reference
System.out.print(" Ford: " + posFord);
System.out.print(" Chevy: " + posChevy);
}


System.out.println("");



/**
* Checks If Ford Has Won
* Prints Out That Ford Has Won
**/
if ( posFord >= 70 ) {
System.out.println (" The Ford Has Won ");
break;
}

/**
* Checks If Chevy Has Won
* Prints Out That Chevy Has Won
**/
if ( posChevy >= 70 ) {
System.out.println (" Chevy Has Won ");
break;
}

//Speed Of Race
try {
Thread.sleep (00); //Change The Value For Speed Of Race ( ms )
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
}
}


If there is anything that I could do to improve it, please let me know!