Java Program on Free Coffee Cups – This particular article talks about the Java Program on Free Coffee Cups along with suitable examples as well as the sample output.
Free Coffee Cups (Per 6 coffee cups I buy, I get the 7th cup free. In total, I get 7 cups)
This code is to calculate the free number of coffee cups the user gets for a certain number of cups bought using Java language.
- The problem here is to calculate the free number of cups the user gets for a specified number of cups bought by the user. In this particular case, the user gets 1 cup free for every 6 cups bought.
- The input here is the number of coffee cups bought by the user.
- The output is the total number of cups the user gets including the free coffee cups (example: If the user buys 12 cups, he gets 2 cups free as per the Buy 6 Get 1 Free offer, and hence the output will be 12+2 = 14 cups).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; class CoffeeCups { public static void main(String arg[]) { int n; Scanner sc=new Scanner(System.in); System.out.println("Enter number of cups :"); n=sc.nextInt(); System.out.println("For ("+n+") cups the total number of cups i would get -->"+totalCups(n)); } static int totalCups(int n) { return (n/6+n); } } |
Output – 1:
- Solution:
- In the main method, int n is declared. After that, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java.
- Scanner class is part of the java.util package and hence the import statement, in the beginning, is stated to import the functionality of the specified class.
- The next line prints a statement to the console instructing the user to enter a number.
- The .nextInt() method is called by the Scanner object sc. This method reads an int value input by a user and stores it to the int variable n.
- Within the print statement in the last line, the method totalCups is called and n is passed in as the argument.
1 2 3 |
static int totalCups(int n) { return (n/6+n); } |
- In this method, the parameter n is divided by 6 to find the number of free cups and then added to n which is the number of cups bought by the user. The total of free cups and bought cups is calculated, returned, and printed out to the console.
1 2 3 |
Enter number of cups : 6 For (6) cups the total number of cups i would get -->7 |
- Here, the user buys 6 cups. As per the calculation in the totalCups method : 6/6 + 6 = 1 + 6 = 7 cups.
- Thus, the user gets 7 cups in all as per the free cups offer.
Output – 2:
1 2 3 |
Enter number of cups : 14 For (14) cups the total number of cups i would get -->16 |
- Here, the user buys 14 cups. As per the calculation in the totalCups method : 14/6 + 14 = 2 + 14 = 16 cups.
- Thus, the user gets 16 cups in all as per the free cups offer.