We then introduced decision making into the computer's vocabulary. That is, the computer's calculations and processing will be determined by the input to the program. We began by reviewing a familiar problem.
NOTE: All of the following require client classes.
Example 1. Write a program that takes the user's income as input and then calculates and outputs the resulting tax.
//File: Taxes.java
import java.text.DecimalFormat;
import CSLib.*;
public class Taxes
{
public static void compute()
{
//Input dialog with user
InputBox in = new InputBox (
"Salary Input" );
in.setPrompt ( "How much did you make last
year?" );
double salary = in.readDouble
();
//Calculate the tax due
final double RATE = 0.2; //20%
Tax Rate
double tax = RATE * salary;
//Output the results
OutputBox out = new OutputBox
( "Your Taxes" );
out.setSize ( 250, 75 );
out.setLocation ( 300, 300 );
DecimalFormat guy = new
DecimalFormat ( "0.00" );
out.println ( "Your income was: $ " +
guy.format ( salary ) );
out.println ( "Your tax due is: $ " +
guy.format ( tax ) );
}
}
Example 2. Modify the previous program to accommodate a 2-tiered tax structure.
//File: Taxes2.java
import java.text.DecimalFormat;
import CSLib.*;
public class Taxes2
{
public static void compute()
{
//Input dialog with user
InputBox in = new InputBox (
"Salary Input" );
in.setPrompt ( "How much did you make last
year?" );
double salary = in.readDouble
();
//Calculate the tax due
final double RATE1 = 0.15;
//15% Tax Rate
final double RATE2 = 0.25;
//25% Tax Rate
final double BRACKET =
50000.0; //separates low income
//from
high income
double tax;
RATE1 = 0.2;
//if salary is under 50000 then
if (salary < BRACKET)
tax = RATE1 * salary;
//or else
else
tax = RATE1 * BRACKET
+
RATE2 * (salary - BRACKET);
//Output the results
OutputBox out = new OutputBox
( "Your Taxes" );
out.setSize ( 250, 75 );
out.setLocation ( 300, 300 );
DecimalFormat guy = new
DecimalFormat ( "0.00" );
out.println ( "Your income was: $ " +
guy.format ( salary ) );
out.println ( "Your tax due is: $ " +
guy.format ( tax ) );
}
}
Note that the calculation section has grown from a one-liner to a if-else
statement taking several lines.
We then considered the problem of converting a score between 0 and 100 into a corresponding letter grade.
Example 3.
//File: Grades.java
import CSLib.*;
public class Grades
{
public static void compute()
{
//input score
InputBox in = new InputBox (
"Score" );
in.setPrompt ( "Enter score (between 0 and
100)" );
int score = in.readInt ();
//calculate letter grade
char grade = ' '; //letter
if ( score >= 90 &&
score <= 100 )
grade = 'A';
else if ( score >= 80
&& score < 90 )
grade = 'B';
else if ( score >= 70
&& score < 80 )
grade = 'C';
else if ( score >= 60
&& score < 70 )
grade = 'D';
else if ( score >= 0
&& score < 60 )
grade = 'F';
//output results
OutputBox out = new OutputBox
( "Grade Conversion" );
out.println ( "Your score was " +
score );
out.println ( "Your grade is " +
grade );
}
}