Food and Drink

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Write a program that will use Scanner to read in the price of a sandwich and a drink. Output the amounts. Calculate and output tax (assume 5% on everything). Then output a receipt as shown.
Sample output with sandwich 5.99 and drink 1.99:

 Cost of Sandwich:
 [DrJava Input Box]
Cost of Drink:
 [DrJava Input Box]
Food cost: 5.99
Drink cost: 1.99
Taxes: 0.399
Total: 8.379000000000001
Programmed by A. Student
**End of Program** 

Extra: Once you get this program working, try rounding the taxes to two decimal places.

 

Using Scanner for input

Wiki chars03.jpg

Solution

Before you can use Scanner, you must import the relevant package.

 import java.util.Scanner; 

Your next step should be to declare variables. For this program, you will only need three; one each for the cost of the food, the cost of the drink, and the tax.

 double foodCost;                     //food amount
double drinkCost;                    //drink amount
double tax;                          //taxes (at 5%) * This really should be a final--next week! 

Now you must create an instance of Scanner. Here we call it keyboard, which is pretty standard because the input will come from the keyboard. But it can be named anything. This will allow the program to read input from the user.

 Scanner keyboard = new Scanner (System.in) ; 

The next step will prompt the user for input using System.out and accept input from the user with Scanner. The method .nextDouble() will cause an error if anything other than a double is input. If the input is a double, it will store it in foodCost and drinkCost respectively.

 System.out.println("Cost of Sandwich:");
foodCost = keyboard.nextDouble();
        
System.out.println("Cost of Drink:");
drinkCost = keyboard.nextDouble(); 

In the final step, the program should output all data in a readable way and indicate that the program is complete. Congratulations, you should now have a program that will calculate tax on a sandwich and a drink. Use it with the Tip Calculator for the full dining experience.

 System.out.println("Food cost: " + foodCost + "\nDrink cost: "  + drinkCost + "\nTaxes: " + tax 
                           + "\nTotal: " + (foodCost + drinkCost + tax));                                                
System.out.println("Programmed by A. Student");
System.out.println("**End of Program**"); 

Code

Solution Code

Back to the Program-A-Day homepage