Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- * This program calculates gratuity for a purchase based on the purchase amount and gratuity rate.
- * Solution to programming exercise 5 from chapter 2 from page 70.
- *
- * Here is the pseudocode :
- *
- * gratuity rate <- prompt user for validated double input using try/catch
- * purchase amount <- prompt user for validated double input using try/catch
- *
- * gratuity amount <- purchase amount * gratuity rate/100
- * purchase total <- gratuity amount + purchase amount
- *
- * Inform the user of their gratuity amount and total amount, allow user to run program again if they press "0'
- *
- */
- public class U1_Problem5 {
- public static void main(String[] args){
- while(true) {
- interactWithUser();
- Scanner scan = new Scanner(System.in);
- System.out.print("Please press 0 if you would like to go again. ");
- if (scan.nextInt() != 0){
- break;
- }
- }
- System.out.println("Goodbye!");
- }
- private static void interactWithUser(){
- calculateAndDisplayTotal(
- getDouble("Please enter amount spent!"),
- getDouble("Please enter gratuity rate!")
- );
- }
- // Use try/catch to receive a validated double as input to a prompt.
- private static double getDouble(String prompt) {
- double amount = 0;
- String currentInput;
- boolean amountSelected = false;
- Scanner scan = new Scanner(System.in);
- while (!amountSelected) {
- System.out.print(prompt + " ");
- currentInput = scan.nextLine();
- try {
- amount = Double.valueOf(currentInput);
- amountSelected = true;
- } catch (NumberFormatException e) {
- System.out.println(
- "Sorry, I can only understand if you enter a single number, not " + currentInput +
- ". Please try again!"
- );
- }
- }
- return amount;
- }
- // Calculate gratuity amount and total amount based of amount spent and gratuity percentage.
- // Inform user of gratuity amount and total amount spent.
- private static void calculateAndDisplayTotal(double amountSpent, double gratuityPercentage){
- double gratuity = amountSpent * gratuityPercentage/100;
- double total = amountSpent + gratuity;
- System.out.println(
- "Since you spent " + amountSpent + " with a gratuity rate of " + gratuityPercentage + "%," +
- " your gratuity is " + gratuity + " and your total is " + total + "!"
- );
- }
Add Comment
Please, Sign In to add comment