In: Computer Science
Write a code snippet to pre-sell a limited number of movie tickets. Each
buyer can buy as many as 6 tickets. No more than 20 tickets can be sold.
Prompt the user for the desired number of tickets and then display the
number of remaining tickets. Repeat until all tickets have been sold,
and then display the total number of buyers.
**********IN JAVA**********
Java code
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int totalticketsleft=20;
int temptickettobuy=0;
Scanner sc=new Scanner(System.in);
while(totalticketsleft!=0)
{
System.out.println("How many tickets?");
temptickettobuy=sc.nextInt();
if(temptickettobuy>6)
{
System.out.println("Ticket count must be less than or equal to
6.");
}
else
if(temptickettobuy<=totalticketsleft)
{
totalticketsleft -=temptickettobuy;
System.out.println("Tickets remaining: "+totalticketsleft);
}
else
{
System.out.println("Tickets left: "+totalticketsleft);
System.out.println("Try again");
}
}
}
}
Sample output
How many tickets?
7
Ticket count must be less than or equal to 6.
How many tickets?
10
Ticket count must be less than or equal to 6.
How many tickets?
5
Tickets remaining: 15
How many tickets?
6
Tickets remaining: 9
How many tickets?
4
Tickets remaining: 5
How many tickets?
6
Tickets left: 5
Try again
How many tickets?
3
Tickets remaining: 2
How many tickets?
3
Tickets left: 2
Try again
How many tickets?
2
Tickets remaining: 0