Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: for loop with random numbers

1. ## for loop with random numbers

Assume that vehicles are going through a two-way traffic intersection. There are three types of vehicles: car, motor bikes and trucks. Generate a series of 10 random integers, between 1 and 3, inclusive. The numbers represent the type of vehicle as stated below:

Number Vehicle Category
1 Car
2 Motor bikes
3 Trucks

Write a program, using a for loop, to count how many vehicles going through the traffic intersection are cars, motor bikes and trucks. Then, the program should print out the numbers for each vehicle category. There is no user input for this program. How do i do it so they will add up the sum of each vehicle? Thank you.

The answer should be something like
Number of cars = X
Number of motor bikes = Y
Number of Trucks = Z

but i'm getting
Total number of vehicle:
cars
motorbikes
motorbikes
cars
Trucks
Trucks
motorbikes
motorbikes
Trucks
cars

public static void main(String[] args) {
int countCar = 0;
int countBike = 0;
int countTruck = 0;
int all=0;

Scanner sc = new Scanner (System.in);
System.out.println("Total number of vehicle:");

for (int series = 1; series<=10; series++) {

all = (int) (Math.random()*3)+1;

if (all==1)
{
System.out.println(" cars " );
}
else if (all==2)
{
System.out.println(" motorbikes " );
}
else if (all==3)
{
System.out.println(" Trucks " );
}
}
}
}

2. You dont need to display the results of each iteration of the loop, just the end and final result.

Code:
```if (all==1)
{
countCars++;
}
else if (all==2)
{
countBikes++;
}
else if (all==3)
{
countTrucks++;

System.out.println("Total Cars: " + countCars);
System.out.println("Total Bikes: " + countBikes);
System.out.println("Total Trucks: " + countTrucks);
}
}
}
}```

3. you actually want to move that out of the for loop and print after all the for loop has completed. this will still print each iteration, it will just be in order this time. :P

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•