Chapter 15
Selectors
15.1 Two-Way Branching Instructions
- The true part is executed if and only if the condition holds:
if ( <condition> ){ <true part> }
if( a > b) {
temp=a; a=b; b=temp;
}
- Either the true or the false part are executed:
if ( <condition> ) { <true part> }
else { <false part> }
if( a > b) {
max = a;
} else {
max = b;
}
- The braces are optional when a single instruction is enclosed.
15.2 Multi-Way Branching Instructions
- General format:
switch ( <integer expression>) {
case <integer constant 1>: <part 1>
................................
case <integer constant n>: <part n>
default: <default part>
}
switch( i ) {
case 1: System.out.println( "me" );
case 2: System.out.println( "me too" );
default: System.out.println( "and me" );
}
- The ‘break’ instruction terminates the execution of the switch construct.
switch( i ){
case 11: System.out.println( "me" );
break;
case 2: System.out.println( "or me" );
break;
default: System.out.println( "otherwise me" );
}
- The default case is optional. If no case holds, the switch terminates.
switch( i ){
case 11: System.out.println( "me" );
break;
case 2: System.out.println( "or me" );
}
15.3 Conditional Expressions
Exercises
15.4 Assignment #20: Branching Instructions
Due: Mo, June 2, midnight
Download the taxes.java program from the web page, and provide the missing code to the ‘int compute(int wages, boolean married, int children, boolean
old, boolean blind, boolean student, boolean citizen)’ method. The method should compute the taxes to
be paid for income provided by wages, according to the following criteria.
- Every taxpayer may deduct $10,000 from the income.
- Married taxpayer may deduct extra $1,000 from the income.
- If the above deductions are greater than the income, no taxes are owed.
- If the taxable portion of the income is smaller than $10,000, a tax rate of 9% should apply.
- If the taxable portion of the income is $10,000 or more, a tax rate of 9% should apply on the first $10,000 and a tax
rate of 12% should apply on the remainder amount.
- The tax liability is to be reduced by a percentage equal to the number of children plus the square
of the number of following categories that apply: age of 65 or more, blind, student. For instance, a
blind student of age 35 with three children is eligible for 7% (= 3 + 22) reduction in tax payments.
- Non-citizens should add $100 to their tax bill, if they are not blind.
Assume ‘lab20’ for the submit command, and submit your ‘taxes.java’ program.
Note: Files that fail to compile, and execute when applicable, will not be examined. They will be awarded a grade
of 0 points.