Latest :

Java : Free Coffee Cups Program | Java Programs

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).
 

Output – 1:

  • Solution:
  1. 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.
  2. 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.
  3. The next line prints a statement to the console instructing the user to enter a number.
  4. 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.
  5. Within the print statement in the last line, the method totalCups is called and n is passed in as the argument.

 

 

  1. 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.

 

 

  • 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:

 

  • 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.
x

Check Also

Java Program To Display Transpose Matrix | 3 Ways

Java Program to display/print the transpose of a given matrix.  The following program to print ...