Java Arithmetic Operator calculate tips

Question

We would like to write a program that reads the subtotal and the gratuity rate.

Then compute the gratuity and total.

For example, if the user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gratuity and $11.5 as total.

import java.util.Scanner;

public class Main {

  public static void main(String[] Strings) {

    double gratuityRate, gratuityTotal, total, subtotal;

    Scanner input = new Scanner(System.in);

    //your code here

  }// ww w .ja v a2  s  .c o m
}


import java.util.Scanner;

public class Main {

  public static void main(String[] Strings) {

    double gratuityRate, gratuityTotal, total, subtotal;

    Scanner input = new Scanner(System.in);

    System.out.print("Please enter the subtotal and gratuity rate: ");
    subtotal = input.nextDouble();
    gratuityRate = input.nextDouble();

    gratuityTotal = subtotal * gratuityRate * .01;
    total = subtotal + gratuityTotal;

    System.out.print("The gratuity is $" + gratuityTotal + " and total is $" + total);

  }
}

Note

To define a method for the calculation:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the subtotal and gratuity rate: ");
    double subtotal = input.nextDouble();
    double gratuityRate = input.nextDouble();

    double gratuity = calculateGratuity(subtotal, gratuityRate);
    double total = calculateTotal(subtotal, gratuity);

    System.out.printf("The gratuity is $%.2f and total is $%.2f\n", gratuity, total);
  }/*from  w w w.  j a v a  2 s .com*/

  private static double calculateGratuity(double subtotal, double gratuityRate) {
    gratuityRate /= 100.0;
    return subtotal * gratuityRate;
  }

  private static double calculateTotal(double subtotal, double gratuity) {
    return subtotal + gratuity;
  }
}



PreviousNext

Related