Actually, the code from last time can be simplified considerably by noting that some of the tests are unnecessary. In fact, the if statement can be rewritten as follows (See Grades.java):
if
((score > 100) || (score < 0))
{
out.println ("You
DUMMY!");
System.exit(1);
}
else if (score >= 90)
{
grade='A';
}
else if (score >= 80)
{
grade='B';
}
else if (score >= 70)
{
grade='C';
}
else if (score >= 60)
{
grade='D';
}
else
{
grade='F';
}
You may have to think about the new version for awhile, but you'll see that by the time the computer checks for "A"s, it knows the score is no bigger than 100. If it weren't, it would have generated the "..DUMMY!" message and quit. As you go down the if statement, similar logic prevails.
Lab Exercise. (p 104/4.3) Write a program that computes the interest rate for an auto loan given the term of the loan (in months). Loans for a term of 24 months or less have a rate of 0.9 percent; 36-month loans carry a rate of 2.9 percent, 48-month loans a rate of 4.9 percent, and 60-month loans a rate of 6.9 percent. My solution is available only when you've exhausted your creativity.
Lab Exercise. (p 104/4.6) Write a program that calculates the entry fee for the local art museum. The fee is calculated as follows: children under 5 yearss, free; adults 65 years and older, $1.50; all others, $2.50. Your program should display the entryFee (of type double) based on the variable ageOfEntrant (of type int). Don't look yet, but we'll check my solution when you're done.
We continued our discussion of SELECTION structures; i.e., those programming structures that ask the computer to select one path over another. In particular, the if-else and switch() statements fall into that category.
//File: Grades2.java
import CSLib.*;
public class Grades3
{
public static void main (String [] args)
{
InputBox in = new InputBox();
in.setPrompt("What was the score? ");
int score = in.readInt();
OutputBox out = new
OutputBox();
char grade=' ';
if ((score > 100) || (score <
0))
{
out.println ("You
DUMMY!");
}
else
//NOTE: 9 / 4 = 2 (the
quotient)
// 9
% 4 = 1 (the remainder)
switch
(score / 10)
{
case 10:
case 9: grade='A';
break; //you need these to
FORCE out of switch
case 8: grade='B';
break;
case 7: grade='C';
break;
case 6: grade='D';
break;
default: grade='F';
}
out.println ("Your
score is: " + score);
out.println ("Your
grade is: " + grade);
}
}


Note that the break statements exit the switch statement and continue through the program. Although they are not required to make the program run, they are absolutely necessary to achieve reasonable results. If they are absent, EVERYONE WILL RECEIVE A F! Try it. With no break's, the flow of execution will fall through to the last assignment statement, grade = 'F'.