Advertisement
Guest User

ShoppingCart

a guest
Oct 4th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. import java.text.DecimalFormat;
  2. import java.util.Scanner;
  3.  
  4. public class ShoppingCart {
  5.  
  6. // "Attributes"
  7. private double taxRate;
  8. private double preTaxTotalPrice;
  9. private double totalPrice;
  10.  
  11. // Constructor
  12. public ShoppingCart() {
  13. // Set the variables to their default values
  14. taxRate = 0D;
  15. preTaxTotalPrice = 0;
  16. totalPrice = 0;
  17. }
  18.  
  19. // "Operations"
  20. public double getTaxRate() {
  21. // Just a simple getter
  22. return taxRate;
  23. }
  24.  
  25. public void setTaxRate(double taxRate) {
  26. // Just a simple setter
  27. this.taxRate = taxRate;
  28. }
  29.  
  30. public void getInput(Scanner scanner) {
  31. System.out.println("Enter the name, quantity, and price of the item."); // Prompt the user
  32. String name = scanner.next(); // Get first the string,
  33. int quantity = scanner.nextInt(); // And then the integer
  34. double price = scanner.nextDouble(); // And then the double
  35. addItem(name, quantity, price); // addItem using those three values
  36. }
  37.  
  38. public void addItem(String item, int quantity, double price) {
  39. preTaxTotalPrice += quantity * price; // Add the price times the quantity to the pTTP
  40. totalPrice = preTaxTotalPrice * (1 + taxRate); // Multiple the pTTP times 1.(taxRate) to get tP
  41. }
  42.  
  43. public String getPreTaxTotalPrice() {
  44. // I like using DecimalFormat over the way mentioned in the hint
  45. return "$" + new DecimalFormat("#.##").format(preTaxTotalPrice);
  46. }
  47.  
  48. public String getTotalPrice() {
  49. // Identical to gPTTP outside of the variable being formatted
  50. return "$" + new DecimalFormat("#.##").format(totalPrice);
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement