Guest User

Untitled

a guest
Jun 17th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /**
  4. * This program calculates gratuity for a purchase based on the purchase amount and gratuity rate.
  5. * Solution to programming exercise 5 from chapter 2 from page 70.
  6. *
  7. * Here is the pseudocode :
  8. *
  9. * gratuity rate <- prompt user for validated double input using try/catch
  10. * purchase amount <- prompt user for validated double input using try/catch
  11. *
  12. * gratuity amount <- purchase amount * gratuity rate/100
  13. * purchase total <- gratuity amount + purchase amount
  14. *
  15. * Inform the user of their gratuity amount and total amount, allow user to run program again if they press "0'
  16. *
  17. */
  18. public class U1_Problem5 {
  19.  
  20. public static void main(String[] args){
  21. while(true) {
  22. interactWithUser();
  23. Scanner scan = new Scanner(System.in);
  24. System.out.print("Please press 0 if you would like to go again. ");
  25. if (scan.nextInt() != 0){
  26. break;
  27. }
  28. }
  29.  
  30. System.out.println("Goodbye!");
  31.  
  32. }
  33.  
  34. private static void interactWithUser(){
  35. calculateAndDisplayTotal(
  36. getDouble("Please enter amount spent!"),
  37. getDouble("Please enter gratuity rate!")
  38. );
  39. }
  40.  
  41. // Use try/catch to receive a validated double as input to a prompt.
  42. private static double getDouble(String prompt) {
  43. double amount = 0;
  44. String currentInput;
  45. boolean amountSelected = false;
  46. Scanner scan = new Scanner(System.in);
  47.  
  48. while (!amountSelected) {
  49. System.out.print(prompt + " ");
  50. currentInput = scan.nextLine();
  51. try {
  52. amount = Double.valueOf(currentInput);
  53. amountSelected = true;
  54. } catch (NumberFormatException e) {
  55. System.out.println(
  56. "Sorry, I can only understand if you enter a single number, not " + currentInput +
  57. ". Please try again!"
  58. );
  59. }
  60. }
  61.  
  62. return amount;
  63. }
  64.  
  65. // Calculate gratuity amount and total amount based of amount spent and gratuity percentage.
  66. // Inform user of gratuity amount and total amount spent.
  67. private static void calculateAndDisplayTotal(double amountSpent, double gratuityPercentage){
  68.  
  69. double gratuity = amountSpent * gratuityPercentage/100;
  70. double total = amountSpent + gratuity;
  71.  
  72. System.out.println(
  73. "Since you spent " + amountSpent + " with a gratuity rate of " + gratuityPercentage + "%," +
  74. " your gratuity is " + gratuity + " and your total is " + total + "!"
  75. );
  76. }
Add Comment
Please, Sign In to add comment