### Programming Example: tax computation

• Introduction

• In this webpage, we will study a programming example using the conditional statements (if and if-else) to write a Java program to compute the tax owed.

• Formula to compute the tax owed

• Decision diagram to compute taxes owed:

• Example 1: someone single earning \$40,000 pays:

 15% of \$21,450,    plus 28% of (\$40,000 − \$21,450)

Graphically:

• Example 2: someone single earning \$60,000 pays:

 15% of \$21,450,                         plus 28% of (\$51,900 - \$21,450),      plus         31% of (\$60,000 - \$51,900)

Graphically:

• Algorithm:

Define the following constants:

 ``` S1 = 21450 S2 = 30450 M1 = 35800 M2 = 86500 ```

Structure diagram:

• Example input: status = 'S' and income = 40000

• The tax computation algorithm in Java:

(The whole program is too large to show here).

 ``` if ( status == 'S' ) { // ***** single if ( income <= S1 ) tax = RATE1 * income; else if ( income <= S2 ) tax = RATE1 * S1 + RATE2 * (income - S1); else tax = RATE1 * S1 + RATE2 * (S2 - S1) + RATE3 * (income - S2); } else { // ***** married if ( income <= M1 ) tax = RATE1 * income; else if ( income <= M2 ) tax = RATE1 * M1 + RATE2 * (income - M1); else tax = RATE1 * M1 + RATE2 * (M2 - M1) + RATE3 * (income - M2); } ```

• Constants used in the program:

 RATE1 = 0.15          (Tax rate)             RATE2 = 0.28 RATE3 = 0.31 S1 = 21450           (Income brackets) S2 = 51900 M1 = 35800 M2 = 86500

• Java program:

 ``` import java.util.Scanner; public class ComputeTax { public static void main(String[] args) { final double RATE1 = 0.15; // Tax rates final double RATE2 = 0.25; final double RATE3 = 0.31; final double S1 = 21450.0; // Tax brackets for single final double S2 = 51900.0; final double M1 = 35800.0; // Tax brackets for married final double M2 = 86500.0; char status; double income = 0; double tax = 0; Scanner in = new Scanner(System.in); // Construct Scanner object System.out.print("Enter status (S or M) = "); status = in.next().charAt(0); // Read in status System.out.print("Enter income = "); income = in.nextDouble(); // Read in income >>>> Insert the Tax Computation Algorithm (see above) here <<<< System.out.println("Tax = " + tax); } } ```