Hi!
I'm really fed up with my program. I'm trying to write a JAVA simulation of a traffic jam. In the beginning the user inputs the length a of Road n (problem with the constructor) and the number of cars c. The Road is an object- simply an array filled with 1 or 0 in the beginning. The constructor is supposed to create such a road of length n with c cars (values 1 in array) putting them on it in random places (starting from beginning).
To do this I wrote another piece of code which generates randomly 0 or 1. It works.
Then I try to do it for two cases- where there are more empty spaces and when there are more cars .... Then starting from the beginning of the array the program puts 0 or 1 into each position. When it reaches the value of cars, the for-loop terminates and leaves the rest of the road blank. This is fine for me. In this case that would be the road I would want to use. However sometimes generating a lot of 0s, the for loop could get to the end of the road not putting all the cars into their places. Thats why I use the do while loop- to check that in the end and if it is the case to try again. The problem is that it never terminates. After a road is made and "allocated" clearly prints as equal to c it goes back and starts all over. What should I do in this case?
This is the code:
class Road {
private int n;
private int c;
private int road[];
private int allocated;
private int assigned;
/// constructor for road taking length and number of cars putting them down randomly
public Road(int n, int c){
this.road = new int[n];
/// if c>(n/2) then allocate 0s, if c<=n/2 allocate 1s
if(c < (n/2)){
do{
int allocated = 0;
for(int i = 0; ((allocated < c) && (i < n)); i++){
this.road[i]=binaryGenerator();
if(this.road[i]==1) {
allocated = allocated +1;
}
}
System.out.println("T "+ allocated +" " + c);
}
while(allocated < c);
}
if(c >= (n/2)){
do{
int assigned = 0;
for(int i = 0; ((assigned < (n-c)) && (i < n)); i++){
this.road[i]=binaryGenerator();
if(this.road[i] == 0) {
assigned = assigned +1;
}
}
}
while(assigned < (n - c));
}
}