In: Computer Science
Write a code snippet for the following:
You need to control the maximum number of people who can be in a
restaurant at any given time. A group cannot enter the restaurant if they
would make the number of people exceed 100 occupants. Use random numbers
between 1 and 20 to simulate groups arriving to the restaurant. After each
random number, display the size of the group trying to enter and the number
of current occupants. As soon as the restaurant holds the maximum number, output
that the restaurant is full and quit.
*********IN JAVA************
In the code, we have generated the random numbers between 1 and 20 with the help of Random class. Secondly, a while loop checks for the condition for threshold and continuously adds the incoming group to the total number of people inside the restaurant. The complete code is given below:
import java.util.Random; import java.util.Scanner; public class Restaurant { private static int peopleInRestaurant; private static int threshold = 100; private static int group; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("People in restaurant: 0"); Random num = new Random(); while(peopleInRestaurant <= threshold){ group = 1+num.nextInt(20); System.out.println("Size of the group trying to enter: "+ group); if(peopleInRestaurant+group > 100){ System.out.println("Restaurant is full"); return; } peopleInRestaurant = peopleInRestaurant + group; System.out.println("Total number of occupants inside restaurant: "+peopleInRestaurant); } System.out.println("Restaurant is full"); } }