control structures - school of computing and … · web viewwrite a java program that can be used...

85
CHAPTER 1................................................................... 2 CHAPTER 2................................................................... 2 CHAPTER 3................................................................... 2 CHAPTER 4 CONTROL STRUCTURES................................................3 Objectives.................................................................3 INTRODUCTION.................................................................3 SELECTION STATEMENTS..........................................................4 The if Statements...........................................................5 The if .. else Statements......................................................10 Pitfalls............................................................. 15 Pitfall I – Misplacing Semi-colon................................15 Pitfall II – Separating else with semi-colon.....................16 Pitfall III – Failing to block statement properly................17 Pitfall IV – Misusing series of if statements....................18 Pitfall V – Misrepresenting nested if statements.................19 Pitfall VI Misusing = and ==.....................................21 Rules Governing the if Statement.....................................21 The switch Statement........................................................24 Pitfalls............................................................. 32 Pitfall I – Forgetting the parentheses...........................32 Pitfall II – Forgetting the braces...............................32 Pitfall III – Forgetting the break keyword.......................32 Rules Governing the Switch Statement.................................35 ITERATIVE STATEMENTS.........................................................39 The while Statement.........................................................39 Nested while Loop.................................................... 46 The do…while Statement..................................................... 58 The for Statement..........................................................60 Nesting for Loops.................................................... 65 Scope of a Loop control variable.....................................66 PitFall.............................................................. 67 Pitfall I – Updating the loop variable incorrectly...............67 Pitfall II – Modifying the loop variable in loop body............67 SUMMARY....................................................................70 Exercises................................................................ 71

Upload: phamnguyet

Post on 05-May-2018

219 views

Category:

Documents


2 download

TRANSCRIPT

CHAPTER 1..................................................................................................................................................................2

CHAPTER 2..................................................................................................................................................................2

CHAPTER 3..................................................................................................................................................................2

CHAPTER 4 CONTROL STRUCTURES.................................................................................................................3

Objectives..............................................................................................................................................................3INTRODUCTION...........................................................................................................................................................3SELECTION STATEMENTS............................................................................................................................................4

The if Statements..................................................................................................................................................5The if .. else Statements......................................................................................................................................10

Pitfalls.............................................................................................................................................................15Pitfall I – Misplacing Semi-colon.........................................................................................................15Pitfall II – Separating else with semi-colon..........................................................................................16Pitfall III – Failing to block statement properly....................................................................................17Pitfall IV – Misusing series of if statements.........................................................................................18Pitfall V – Misrepresenting nested if statements..................................................................................19Pitfall VI Misusing = and ==................................................................................................................21

Rules Governing the if Statement...................................................................................................................21The switch Statement...........................................................................................................................................24

Pitfalls.............................................................................................................................................................32Pitfall I – Forgetting the parentheses....................................................................................................32Pitfall II – Forgetting the braces...........................................................................................................32Pitfall III – Forgetting the break keyword............................................................................................32

Rules Governing the Switch Statement..........................................................................................................35ITERATIVE STATEMENTS..........................................................................................................................................39

The while Statement............................................................................................................................................39Nested while Loop..........................................................................................................................................46

The do…while Statement.....................................................................................................................................58The for Statement................................................................................................................................................60

Nesting for Loops...........................................................................................................................................65Scope of a Loop control variable....................................................................................................................66PitFall.............................................................................................................................................................67

Pitfall I – Updating the loop variable incorrectly.................................................................................67Pitfall II – Modifying the loop variable in loop body...........................................................................67

SUMMARY.................................................................................................................................................................70Exercises..................................................................................................................................................................71

CHAPTER 1

CHAPTER 2

CHAPTER 3

2

CHAPTER 4 Control Structures

Objectives

To understand what control structures are and the need for them. To understand the two types control flow – selection and iteration. To understand selection statements – if, if/else and switch. To understand iterative statements – while, do/while, and for.

Introduction

The order in which statements are executed in programs is determined by the controls to which each statement is subjected. Unless otherwise specified, the execution of a program proceeds in a linear fashion, from the first statement to the last; no statement is skipped, and none is repeated. Figure 4.1 shows what happens when statements are executed in sequence; each statement represented by S, is executed in the order in which each is written.

Figure 4.1Program statements executed in sequence.

3

S 1

S 2

S 3

S i

The invocation of methods do not constitute an altering of the control flow, but rather it is an expansion of the statement call, in which case the statement is expanded by the method definition. If we let M represents a method instead of a single statement, as shown in Figure 4.2, then when the method is called, it simply executes its statements, and then re-enters the original linear formation of statements.

Original Linear Formation

Method M() definition

Figure 4.2 Method M is called from the original linear formation

Control structures seek to alter the flow of program statements within a given piece of code. This is carried out using two control structures - selection and iteration.

Selection Statements

Selection statements are those statements that allow for choice to be made. The decision for making a choice is based on the result of a conditional expression. Figure 4.3 represents a decision making process. In this Figure, notice that the result of the conditional expression – representing a decision – is one of the Boolean values, true or false.

4

S 1

S1

Si

S 3

S i

M()

true

false

Figure 4.3 Symbol representing selection.

There are two basic forms of selection statements in Java. These are the if statement and the switch statement.

The if Statements

As we said earlier, the if statement allows us to make choice. The statement has two forms, namely, if without an alternate choice, and if with alternate choice, symbolized by the keyword else. The word if is also a keyword. The general format of the if statement without an alternate choice is as follows:

if ( conditional_expression )a_single_statement;

or

if ( conditional_expression ) {

Two or more statements;}

The interpretation of this form of the if statement is this, if the conditional expression evaluates to true, then the statement or the block of statements that follow the condition will be executed. If the result is false, then the statement or block of statements that follow the condition will be skipped. Figure 4.4 shows conceptually, the format of the if statement that does not have an alternate choice.

true

false

Figure 4.4 An if statement without alternate choice

5

conditional expression

Scondition expression

The following is an example of its usage:

if ( 30 > 25)System.out.println(“That is correct”);

Where the word if is the keyword, and 30 > 25 is the conditional expression that is being tested. In this case the condition evaluates to true, and so the print statement is executed.

Example 4.1

The cost of an international telephone call is a flat fee of $4.00 for up to the first 5 minutes, and $0.25 per minute for any additional minutes. Write a class definition called Telephone that accepts an integer, representing the number of minutes used. Provide a method called calculateBill that calculates customers, bill.

Solution

Name of class Telephone Constants:

o Flat rate $4.00o Cost per additional minutes 0.25o Maximum number of minutes at flat rate, 5

Instance variable – the minutes Constructor:

o Accepts number of minutes spent on each call Method calculateBill()

The total cost of a call is the flat rate up to 5 minutes, and 25 cents * any additional minutes. The condition for the additional expense must be based on the relation between the number of minutes used, and the five minutes for the flat rate. That is:

if (minutes > 5 ) then charge the additional cost.

Listing 4.1 shows the class Telephone. Lines 3 – 4 set up the class constants. Lines 5 – 6 declare the instance variables. The constructor which receives a single value representing the number of minutes used, spans Lines 7 – 11. Notice that the initial charge is $4.00. Any additional minutes must be charged. The method calculateBill(), shown on Lines 12 – 15, determines if the number of minutes used, exceed the maximum number of minutes at the flat rate. Notice also that the test does not indicate an alternate choice.

1. public class Telephone2. {3. private final static float FLAT_RATE = 4.0F,

RATE = 0.25F;4. private final static intMAX_MINUTES = 5;5. private int minutes;

6

6. private float charges;

7. public Telephone(int minutes)8. {9. this.minutes = minutes;10. charges = FLAT_RATE;11. }

12.public void calculateBill()13.{14.if (minutes > MAX_MINUTES)

charges = charges + (minutes - MAX_MINUTES)*RATE;15.}

16. public float getBill() 17. {18. return charges; 19. }20. }

Listing 4.1 Implementing the if without an alternative choice.

Listing 4.2 shows a typical test class. Line 10 simply creates a customer object that spends m number of minutes on a call. Line 11 calls the calculate method, and Line 12 calls the getBill() method in order to print the bill for the customer.

1. import java.text.NumberFormat;2. import java.util.Scanner;

3. public class TestTelephone4. {5. public static void main(String[] arg)6. {7. NumberFormat nf = NumberFormat.getCurrencyInstance();8. Scanner s = Scanner.create(System.in);9. int m = s.nextInt();10. Telephone t = new Telephone(m);11. t.calculateBill();12. System.out.println("Your bill is " + nf.format(t.getBill()));13. s.close();14. }15. }

Listing 4.2 Test class for the class Telephone.

7

If two or more statements depend on the outcome of a conditional expression, then those statements form a block, and they must be enclosed within curly braces. For instance, in the program segment below, the two print statements depend on the outcome of the test in the if statement, as such these statements must be enclosed within the pair of curly brace, as shown below..

if ( 30 > 25 ){

System.out.println(“That is correct”);System.out.println();

}

Again, in this case the conditional expression is evaluated to true, hence, the block of statements is executed.

In Example 4.1 we used a relational expression for the conditional expression. Logical expressions can also be used, as we will see in the next example.

Example 4.2

The ABC Company offers scholarships to individuals who are in need of financial assistance. The company advertises the scholarship nation wide. Preference however, is given to Florida residents who range from 18 years old to 25 years old.

Write a class called Scholarship that accepts the name, age, and the state in which the applicant resides. Include a Boolean instance method called checkEligibility that determines a candidate’s eligibility for a scholarship. The class must also provide methods to retrieve the name and age of those applicants who are selected.

Analysis Name of entity:

o Scholarship.

Member variables:o name, state (String)o age (int).

Things to be done:o Determine eligibility (check the state)o Provide method to return whether or not the individual is eligible (true/false)o Provide methods to return other relevant information such as name and age

To determine eligibility status of an applicant, we must form a logical expression using age and place of residence as operands. That is:

8

state.equals(“Florida”) && age >= 18 && age <= 25

Let us lift the restriction from strict equality on the variable state, to one of ignoring the case, by using the method equalsIgnoreCase(). If we use this method then it will take care of both lowercase and uppercase characters.

Listing 4.3 shows the definition for the class called Scholarship. The instance method checkEligibility(), is central to the class, in that the use of the if statement applies a logical expression. This is demonstrated on Line 13. The if statement uses that Boolean expression to determine if the individual is eligible for a scholarship. If the result of the test is true, then the Boolean variable eligible is assigned the value true, otherwise it is false by default. You should also notice that this form of using the if statement has no alternate choice.

public class Scholarship1. {2. String name,state;3. int age;4. boolean eligible;

5. public Scholarship(String name, int age, String state)6. {7. this.name = name;8. this.age = age;9. this.state = state;10. }

11.public void checkEligibility()12.{13.if (state.equalsIgnoreCase("Florida") && age >= 18 && age <= 25 )

eligible = true;14.}

15. public boolean isEligible() { return eligible; }16. public String getName() { return name; }17. public int getAge() { return age; }18. }

Listing 4.4 Using if to determine a situation.

The class Scholarship simply determines if the individual is eligible for a scholarship. However, it is left to the test class to determine what information it wants from this class. Suppose we want an output as shown in Figure 4.5

9

Figure 4.5 The desired result from the program.Let us further assume that we want to use three separate print statements to generate this result. Notice that this output only accounts for those individuals who get an award. That is, no mention is made of anyone who does not get an award. This being the case, the test class can call the Boolean method isEligible() in the class Scholarship to determine who gets an award.

The test class is shown in Listing 4.4. The if statement shown on Line 8 simply uses the Boolean result returned by the isEligible() method to determine if the three statements that depend on this outcome must be executed. Once again, notice that this form of using the if statement does not have an alternate choice.

1. public class TestScholarship2. {3. public static void main(String[] arg)4. {5. scholarship s = new scholarship("John Brown", 20, "FLorida");6. s.checkEligibility();7.8. if (s.isEligible())9. {10.System.out.println(s.getName() + " is " + s.getAge() + " years old");11.System.out.println("This person gets a scholarship");12.System.out.println("This person is a Floridian");13.}14. }15. }

Listing 4.4 Using if to determine who is illegible.

The if .. else Statements

The if .. else statement specifies at least one alternate choice. The general format of this statement is as follows:

if (condition1) statement1;

else if (condition2) statement2;

10

::

else if (conditioni )statementi ;

else statement;

Figure 4.6 shows how the if..else statement works. The diagram illustrates that whichever of the conditional expressions results in true, the associated statement or block is executed, and the rest of the statement is skipped. If none of the conditions yields true, then the last block following the last false, is executed.

true

falsetrue

falsetrue

false

Figure 4.6 The if/else construct and how it works.

Example 4.3.

The ABC Company offers scholarships to individuals who are in need of financial assistance. The company advertises the scholarship nation wide. Preferences are given according to the following rules:

Florida residents get 50% of the fund with no age restriction Other US residents get 35% of the fund, but must be 18 to 30 years old International students get 15% of the fund, but the applicant must be 18 to 25 years old.

11

conditional expression

conditional expression

conditional expression

S/block

S/block

S/block

S/block

Write a class called Scholarship that accepts the name, age, the place of residence, and the amount of money that is to be awarded. Include an instance method called checkEligibility, that determines the eligibility of each applicant. The class must also provide methods to retrieve each attribute.Write a test class that reports on applicants’ eligibility status, including those that are ineligible.

Analysis Name of entity

o Scholarship. Possible member variables

o name, state.(String)o age (int)o Boolean variable representing an applicant ‘s origin – florida, usa, international

Things to be doneo Determine eligibility (check the state)o Provide method to return whether or not the individual is eligible (true/false)o Provide methods to return any other useful information

In this exercise we need to identify the three categories of applicants: Floridians, US residents who are non-Floridian, and international applicants.

Note: Eligibility for Floridians is based on place of residency alone. Eligibility for other US residents is based on place of residence, and also on age. Similarly, eligibility for international applicants is based on place of residence, and also on age.

Figure 4.7 shows how the process of checking the eligibility status of each applicant works.

true

false

true

false

true

false

false

12

Florida eligible

USA eligible

International eligible

Process award for Florida

Process award for USA

Process International student award

Figure 4.7 using multi-way testing to check the eligibility status of applicant

For each of these situations we can build the requisite Boolean expressions. That is:

The expression for Floridian is: state.equalsIgnoreCase("Florida”)

For other US citizen::state.equalsIgnoreCase("USA") && age >= 18 && age <= 30

International students: state.equalsIgnoreCase("International") && age >= 18 && age <= 25

We will use the if..else construct to implement these alternative expressions. Against this background it is necessary to maintain the three Boolean variables - florida, usa, international – to store the status of an applicant. Listing 4.5 shows the class Scholarship.

1. public class Scholarship2. {3. private static final double FL = 0.5;4. private static final double US = 0.35;5. private static final double OTHER = 0.15;

6. private String name, state;7. private int age;8. private boolean eligible,florida, usa, international;9. private double award, amount;

10. public Scholarship(String name, int age, String state, double amount)11. {12. this.name = name;13. this.age = age;14. this.state = state;15. this.amount = amount;16. eligible = true;17. }

18.public void checkEligibility()19.{20.if (state.equalsIgnoreCase("Florida"))21.{22.florida = true;23.award = amount * FL;24.}25.else if (state.equalsIgnoreCase("USA") && age >= 18 && age <= 30)26.{27.usa = true;28.award = amount * US;

13

Not eligible

29.}30.else if (state.equalsIgnoreCase("International") && age >= 18 && age <=

25)31.{32.international = true;33.award = amount * OTHER;34.}35.else36.eligible = false;37.}38. public boolean isFloridaEligible() { return florida; }39. public boolean isUsaEligible() { return usa; }40. public boolean isInternationalEligible() { return international; }41. public boolean isEligible() { return eligible; }42. public double getAward() { return award; }43. public String getName() { return name; }44. public int getAge() {return age;}45. }

Listing 4.5 Class Scholarship.

There are several things to observe in Listing 4.5, namely:

1. The central theme of this class is the use of the if..else statement, which is implemented by the method checkEligibility, Lines 18 – 37.

2. The use of the if..else statement is a translation of Figure 4.7.

3. Line 8 shows the Boolean variables that are used to keep track of the eligibility status of each applicant.

4. The variable called eligibility is used to track whether or not any applicant was successful. At the beginning we assume that every applicant is eligible, so we set this variable to true, in the constructor – Line 16. If during the process we find that an applicant is ineligibly, we reset the value to false. As seen on Line 36.

5. The second and third if..else statement, each implements logical expression, instead of simply a relational expression.

6. Each if..else statement comprises a block with two statements, hence these statements are placed within pairs of curly braces. The last else statement comprises only a single statement. This single statement does not require curly.

Listing 4.6 shows a typical test class for the class Scholarship. Notice that after an applicant object has been created, we must call the checkEligibility method.

1. import java.text.NumberFormat;

14

2. import java.util.Scanner;

3. class TestScholarship4. {5. public static void main(String[] arg)6. {7. NumberFormat nf = NumberFormat.getCurrencyInstance();8. Scanner read = Scanner.create(System.in);9. String name = read.next();10. int age = read.nextInt();11. String residency = read.next();12. int amount = read.nextInt();

13. Scholarship s = new Scholarship(name, age, residency, amount);

14. s.checkEligibility();

15. System.out.println(s.getName() + " is " + s.getAge() + " years old " );

16. if (!s.isEligible())17. System.out.println("Applicant is not eligible for scholarship ");18. else19. {20. if (s.isFloridaEligible())21. System.out.println("is a Floridian");22. else if (s.isUsaEligible())23. System.out.println("is a USA student not from Florida");24. else25. System.out.println("is an international student");26. System.out.println("gets a scholarship of " + nf.format(s.getAward()));27. }28. }29. }

Listing 4.6 TestScholarship – a typical test class for the class Scholarship.

In generating the report for each applicant, we must identify the candidate by using once again the if..else statement. In this case however, there is something that is different from the former usage. Inside the first else statement there is an if..else statement. You may wonder why. If the applicant is not eligible, then the first print statement is executed. If this is not the case, then the applicant is eligible. This is represented by the else statement. Since the applicant would be eligible, then we must identify which kind it is. It is against this background we need the if..else statement within the first else statement.

Pitfalls

If you do not fully understand the if statement, you could write codes that either do not compile, or worst, codes that compile but give the wrong answer. In this section you will learn about the common types of mistakes that beginning programmers make, ways by which you can avoid them, and ways you can correct them, if you should make any of them.

15

Pitfall I – Misplacing Semi-colon

The if statement must be viewed as one complete thought, for both the single statement and the block of statements. In the first case, the statement:

if ( 30 > 25 )System.out.println(“That is correct”);

can be written as

if ( 30 > 25 ) System.out.println(“That is correct”);

Similarly the statement:

if ( 30 > 25 ) {

System.out.println(“That is correct”);System.out.println();

}

This means the same as:

if ( 30 > 25 ) { System.out.println(“That is correct”); System.out.println(); }

The indentation is only used for readability, but nothing else. Sometimes beginning students want to regard the if part of the statement as separate from the statement/statement block, so they write the code this way:

if (30 > 200);System.out.println("Wow!!");

This code compiles, but the result is incorrect, since the if statement is followed literally by no statement. Notice the semi-colon following the if clause. In this situation the print statement will be executed regardless of the outcome of the conditional expression.

Pitfall II – Separating else with semi-colon

A second type of pitfall occurs when using the if ..else statement. Consider Listing 4.7.

16

1. class Pitfall2. {3. public static void main(String arg[])4. {5. if (30 > 200);6. System.out.println("Wow!!");7. else8. System.out.println("Ohh!!");9. }10. }

Listing 4.7 Pitfall is using the if ..else construct.

Again if you think of the if as separate for the rest of the statement, and place a semi-colon after the if clause, you will run into even a worst problem. This time the code will not compile, because the compiler considers the following segment to be separate from the if the clause:

System.out.println("Wow!!");else

System.out.println("Ohh!!");

When this happens the compiler complains that the else does not have a corresponding if. Figure 4.8 shows the actual compilation error message.

Figure 4.8 Error because if ..else statement is incorrectly expressed.

Notice that the caret points to the else, suggesting that something is wrong with the way in which the statement is written. In addition, the compiler is telling you that on the preceding line, the else clause does not have an if clause corresponding to it.

Pitfall III – Failing to block statement properly

17

--------------------Configuration: j2sdk1.4.2_03 <Default>-----------C:\ Listing4.5\Pitfall.java:7: 'else' without 'if'

else ^1 error

A third pitfall is failure to enclose a block of statement within curly braces. If a statement were to follow an if statement, such statement would have been executed regardless of the outcome of the test, since the if statement itself is a complete thought. For example, consider the following segment of code:

if ( 30 > 20 )System.out.println(“Yes”);

System.out.println(“Oh well!”);

In this piece of code there are only two statements, the if statement and the second println statements. The second print statement will be executed regardless of the outcome of the if statement. If it was meant that both print statements were to be executed based on the outcome of the if clause, then both of them must be enclosed within a pair of curly braces.

Pitfall IV – Misusing series of if statements

Beginning programmers often times believe that you can use a series of if statements instead of the if..else construct, and still get the correct result. For instance, consider Example 4.4.

Example 4.4

The ABC Company gives wards to its employees for long service to the company. The awards are as follows:

An employee who serves over ten years gets one thousand dollars; anyone who serves eight to ten years gets five hundred dollars; and anyone who serves less than eight years is not entitled to an award.

A beginning programmer who is learning about the if statement might be tempted to believe that a series of if statements can solve this problem, hence they might write code as shown in Listing 4.8, Lines 7 – 9.

1. public class Pitfall42. {3. public static void main(String[] arg)4. {5. int years = 19;6. float award = 0;

7. if (years > 10) award = 1000;

8. if (years >= 8) award = 500;

18

9. if (years > 0 ) award = 0;

10. System.out.println("Your award is " + award);11. }12. }

Listing 4.8 Using series of if statements, instead of using if..else.

Pitfall V – Misrepresenting nested if statements

Another type of mistake is using nested if statements without due care of matching if with else. The construct of the if statement is:

if (condition)S;

where S is any valid Java statement. But what if S itself is an if..else statement, then the construct would now look like the if statement shown below:

if ( condition_1 ) if ( condition_2 )

statement_1;else

statement_2;

Since the second if statement is a substitute for statement S, then the else belongs to the if in this second if statement.

If the statement was written as:

if(condition){

S1;}else

S2;

If S1 is another if statement, then the entire statement is now interpreted as:

if ( condition ) {

if ( condition_2 )

19

S;}else

S;

Example 4.4

A beginning programmer was asked to use the if statement to determine those students who were marginally passing a course and those who were definitely failing. The problem definition went this way:

Any student whose average is more than 70 is passing the course, but those with average less than 75 is marginally passing the course; any student with any other grade is failing the course.

The programmer wrote the code exactly the way is it given in the narrative. Listing 4.9 shows the code produced by the programmer, as seen in the method determineStatus(int grade).

1. class PitFall2. {3. public static void main(String[] arg)4. {5. determineStatus(80);6. }}

7. static void determineStatus(int grade)8. {9. System.out.println("Your average is " + grade );

10. if(grade >70)11. if (grade < 75)12. System.out.println("You are marginally passing the course");13. else14. System.out.println("You are failing course");15. }16. }

Listing 4.9 Erroneous code produced by programmer.

The programmer knows that he has a grade of 80, so he tested his program with his grade. When he ran the program with his grade, to his astonishment his program said that he is failing. See Figure 4.9.

20

Figure 4.9 Erroneous answer.

Pitfall VI Misusing = and ==

Another common mistake that beginning programmer makes is to use = instead of == when comparing two items for equality. Recall that the equal symbol ( = ) is used to assign values, but the double equal symbol ( == ) is used as a relational operator to form a Boolean expression.

For instance, consider the following code:

static void determineStatus(int grade){

if (grade = 80)System.out.println("The values are equal");

}

Notice that the statement grade = 80 is assigning the value 80 to the variable grade and not a relational expression between grade and 80. Hence, the compiler flags this usage as a syntax error. Figure 4.10 shows the actual compilation error message.

Figure 4.10 relational expression required and not an assignment statement.

In this error message the compiler tells us that the if statement is not constructed properly. The third line specifies that a Boolean expression is required, not an assignment statement.

21

C:\ chapter4\Examples\Example4.16\PitFall.java:10: incompatible typesfound : intrequired: boolean

if (grade = 80) ^1 error

The if statement requires Boolean expression.

The Boolean expression must be placed within a pair of parentheses.

A block of statements must be enclosed within curly braces.

The statement(s) can be any valid Java statement including conditional statement also.

When if statements are nested without priority, the else is associated with the inner if.

To prioritize an else clause, you must use curly braces.

Rules Governing the if Statement

Exercises 4a

1. Pitfall I thru VI show common errors make by beginning programmers. Re-write each pitfall so that each compiles and produces the desired result.

2. Study the following class carefully.

class TestIf{

public static void main(String[] arg){

int x = 200, y = 100, z = 50;

if ( x <= y)if (y < z )

y = y * z;else

y = z * x;

System.out.println("x is " + x + " y is " + y);}

}

(a) What will appear on the screen when the program is executed?

(b) If you the if/else statement to the construct shown below, what will be displayed this time?

if ( x <= y){

if (y < z )y = y * z;

22

}else

y = z * x;

3. Given the following code

public class Mystry{

public static void main(String[] arg){

int i = 10, j = 12;if (i < j && (( i = 30)/2) > 5) System.out.println(" i is " + i);

}}

What will appear on the screen when the program is executed?

(a) The code will not compile because the if statement is not properly formed.(b) The code will compile and execute, and i is 30 will be printed.(c) The code will compile and execute, and i is 15 will be printed.(d) The code will compile but nothing will be printed.

4. Given the following code:public class Mystry{

public static void main(String[] arg){

int x = 3; if (x < 5) if (x < 3)

System.out.println("Less than 3"); else if (x > 2 )

System.out.println("Greater than 2"); else

System.out.println("I do not know");}

}

What will appear on the screen when the above program is executed?(a) Less than 3(b) Greater than 2(c) I do not know(d) Nothing will appear on the screen because the code is not indented properly.

5. Use the if..else statement to determine the correct monthly income of a sales associate. Do not use any logical operation in this exercise – use only relational expression.

23

Monthly sales IncomeGreater than or equal to $10,000 $500 plus 15% of salesLess than $10,000 but greater than or equal to $8,000 $400 plus 12% of salesLess than $8,000 but greater than or equal to $6,000 $350 plus 9% of salesLess than $6,000 but greater than or equal to $4,000 $250 plus 5% of salesLess than $4,000 but greater than zero $150 plus 1% of salesNo sales $100

6. Using Exercise 5, write a class called MonthlySalary that accepts an associate’s name and the amount of sales for a given month. Include a method called calculateSalary that uses the if..else statement to determine the associate’s salary. Write a test class called TestSalary to test the class MonthlySalary.

The switch Statement

The switch statement is an alternate method for multi-way selection. The switch statement is a special case of the if..else statement in the sense that it can only test some integral values. This means that the statement cannot test floating-point values or string values. The only values that the switch statement can test are byte, short, int, and char. It does not accept long. The general format of the switch statement is:

switch (selectionVariable){

case value1: statement1;

break;case value2:

statement2;break;

::

case valuei;

statementi;

break;default:

statement;break;

}

With the introduction of the switch statement, are four new reserved words: switch, case, break, and default. Where:

1. The switch expression contains the integral value that is to be matched with the case label values.

2. The case statement provides entry to the statement or set of statements that are to be executed if a match is made. The case label must be a constant. Each case label must be unique.

24

3. The default statement specifies what must be done if no match is made. It is optional, and may be placed anywhere within the scope of the switch statement.

4. The break statement terminates the switch statement.

Example 4.5

Design a class called StudentStatus that displays a student’s status in a university, based on the following codes:Code Student status1 Freshman2 Sophomore3 Junior4 Senior

The class accepts a code number and returns the status of the individual.

Analysis

Name of class o StudentStatus

Instance variables neededo The code (int) o String s that holds the value for the status to be displayed.

Instance method o determineStatus that uses the switch statement to determine the status..o toString method to return the status of the individual.

In order to determine the status of each student, we can start by first making a diagram to depict the situation. See Figure 4.11.

25

code = ..

code == 1

code == 2

code == 3

code == 4Not an undergraduate

Freshman

Sophomore

Junior

Figure 4.11 Diagram depicting the solution to selecting the right option

Listing 4.8 shows the solution to the student status problem. This is in part a direct translation of Figure 4.11.

1 public class StudentStatus2 {3 String s;4 int code;

5 public StudentStatus(int code)6 {7 this.code = code;8 s = "";9 }

10 public void determineStatus()11 {12 switch(code)13 {14 case 1:15 s = "Freshman";16 break;17 case 2:18 s = "Sophomore";19 break;20 case 3:21 s = "Junior";22 break;23 case 4:24 s = "Senior";25 break;26 default:27 s = "Not an undegradute";

26

Senior

28 break;29 }30 }

31 public String toString(){ return s; }32 }

Listing 4.8 Using the switch statement

The central theme to this exercise is the use of the switch statement. The method determineStatus() implements this concept. Line 12 shows how the keyword switch is applied; also, it shows how the selector variable, code, is applied. The body of the switch is enclosed within a pair of curly brace, as shown on Line 11 and Line 29. Notice also, that each case has a unique label – 1, 2, 3, 4 – in this example. The default statement which spans Line 26 thru 28 takes care of any code value that is neither 1, 2, 3, nor 4.

The switch statement can represent logical-OR. The construct representing logical-OR has the following form:

switch(selectorVariable){

case value1:case value2:

S;break; : :

}

The case statements are interpreted as follow:

If the value in the variable called selectorVariable matches case label value1 or if it matches case label matches case label value1 or if it matches case label value2, execute statement S, then execute statement S.

Example 4.6

An internet service provider has three subscription packages for its customers. The packages are as follows:

Package A: For $9.95 per month, 50 hours of access are provided free. Additional hours are charged at $0.12 cents per hour.

Package B: For $14.95 per month, 100 hours of access are provided free. Additional hours are charged at $0.07 hours.

Package C: For $39.95 per month unlimited access is provided.

27

Design a class called InternetServiceProvider that accepts a character and an integer value, where the character represents the package type and the integer value represents the number of hours used. Include a method that determines the package type and calculate each customer’s monthly bill. Note – the number of hours used in a month cannot exceed 720.

Design a test class to implement the class InternetServiceProvider.

The design of this class follows similar pattern to the previous example. As a design consideration, identify the following:

Those values that can be regarded as constants. Separate methods that test for extraneous situations, for example, design methods to test specifically any

value that could be negative, and any value that could exceed the allowable number of hours in an average thirty day month.

A method that is dedicated to determine he charges for each customer. This method uses the switch statement exclusively for the purpose of determining the charges. When we treat the solution this way, the overall solution is not cluttered with extraneous ideas.

Listing 4.9 shows the solution for the class InternetServiceProvider.

1. import java.text.NumberFormat;2. public class InternetServiceProvider3. {4. static double PACKAGE_A = 9.95;5. static double PACKAGE_B = 14.95;6. static double PACKAGE_C = 39.95;7. static int MAX_HOURS = 720;8. int hours; 9. char pakage;10. double charges;11. String message;

12. public InternetServiceProvider(char p, int hours)13. {14. this.hours = hours;15. pakage = p;16. }

17. public boolean isGreaterThanZero() 18. {19. return hours > 0;20. }21. public Boolean exceed720()22. { 23. return hours > MAX_HOURS;

28

24. }

25. public void calculateCharges() 26. {27. switch(pakage)28. {29. case 'a': 30. case 'A':31. message = "PACKAGE A";32. charges = PACKAGE_A;33. if (minutes > 50) charges = charges + (hours - 50) * 0.12;34. break;35. case 'b': 36. case 'B':37. message = "PACKAGE B";38. charges = PACKAGE_B;39. if (minutes > 100) charges = charges + (hours - 100) * 0.07;40. break;41. case 'c':42. case 'C':43. message = "PACKAGE C";44. charges = PACKAGE_C;45. break;46. default:47. message = "No such PACKAGE";48. charges = 0;49. break;50. }51. }

52. public String toString()53. {54. NumberFormat df = NumberFormat.getCurrencyInstance();55. return "Your package is " + message +

"\nYour charge for this month is " + df.format(charges);56. }57. }

Listing 4.9 Using the switch statement in the form of logical-OR.

The use of the switch statement in this exercise places emphasis on the case statement. Since someone could input uppercase letters as well as lower case letters, provision is made for both situations by using the case statement as a logical-OR. For example, see Lines 23 and 24, or Line 29.

Listing 4.10 is a typical test class for the class InternetServiceProvider. It further makes us of the if..else statement in determining a customer’s bill. Notice the use of the nested if concept.

29

1. class TestInternetService2. {3. public static void main(String[] arg)4. {5. InternetServiceProvider t = new InternetServiceProvider('b', 500);

6. if (t.isGreaterThanZero())7. {8. if (t.exceed720 ())9. System.out.println("The number of hours given exceeds the allowable limit");10. else11. {12. t.calculateCharges();13. System.out.println(t);14. }15. }16. else17. System.out.println("Error: cannot calculate charges");18. }19. }

Listing 4.10 Using nested if to determine customer’s bill.

The switch statement can be used to represent logical-AND, as seen in the following construct:

switch(selectorVariable){

case value1:case value2:

:switch(selectorVariable){

case value1:statement;:

break;:

}break; : :

}

30

When we use the switch statement as logical-AND this usage is regarded as nesting the switch statements. That is, a switch statement within another switch statement. The following example shown in Listing 4.11, uses the switch statement to determine what kind of day of the week it is. Notice the use of the logical-OR especially Lines 9 – 12. The switch statement is used again on Line 14. This time its use indicates a logical-AND operation. This means the first switch, shown on Line 7, identifies the kind of days in general, but the second switch, Line 14, identifies specific kind of days.

1. import javax.swing.JOptionPane;

2. public class TheDays3. {4. public static void main(String arg[])5. {6. int day = Integer.parseInt(JOptionPane.showInputDialog("Get an integer 1 - 7"));

7. switch (day)8. {9. case 1:10. case 2:11. case 3: 12. case 4: 13. System.out.println("This is a school day");14. switch(day)15. {16. case 1:17. System.out.println("This is Monday day");18. break;19. case 3:20. System.out.println("This is Wednesday, lab day");21. break;22. default:23. System.out.println("Just another school day");24. break;25. }26. break;27. case 5: 28. System.out.println("Soon it will be weekend");29. break;30. case 6:31. case 7: 32. System.out.println("Weekend is here!!!");33. break;34. default:35. System.out.println("Not a day of the week");36. break;

31

37. }38. }39. }

Listing 4.11 using the switch statement as logical-AND and logical-OR.

Notice that the second switch is nested within the first switch statement. See Lines 14 – 25, the nested switch.

Pitfalls

Very often beginning programmers make several kinds of errors when learning the switch statement. Like the if and if..else they make syntax errors as well as logic errors.

Pitfall I – Forgetting the parentheses

One type of errors that students make, is forgetting the parentheses in the switch clause. As a result they write codes such as the following:

switch day{

case 1:System.out.println("This is a school day");

break;default:break;

}

In this example, notice that the parentheses around the selector variable – day – is missing.

Pitfall II – Forgetting the braces.

A second form of error is forgetting the opening braces following the keyword switch. As a result the practicing programmer writes code such as the following:

switch (day)case 1:

System.out.println("This is a school day");break;

32

default:

break;

Pitfall III – Forgetting the break keyword

Although forgetting the break statement does not constitute syntax error, it represents logic error. Failure to place it when it is required can lead to devastating results.

Example 4.7

Real Estate Licensing School Inc offers four kinds of lessons to participants who want to be licensed to do business in a particular state. The school charges a non-refundable registration fee of $50.00 for each applicant. The fee table for each kind of class is as follows:

Life Insurance $250.00Health Insurance $150.00Mortgage Brokerage $350.00Appraisal $300.00

Requirement – write a program to display the course that the applicant registers for, and the total cost of the course.

Let us assume that two people worked on the program – one writes the test class and the other writes the class that determines the course the applicant registers for, and the total amount of money due.

Programmer A writes a menu driven interface as shown in Listing 4.13.

1. import javax.swing.JOptionPane;

2. public class TestCertification3. {4. public static void main(String[] arg)5. {6. String s = JOptionPane.showInputDialog("1. Life insurance\n2. Health insurance\n"

+"3. Mortgage\n4. Appraisal\nMake selection");7. int x = Integer.parseInt(s);

8. Certification c = new Certification(x);9. c.getCost();10. System.out.println(c);11. }12. }

Listing 4.13 Menu driven interface to the class Certification.

33

Programmer B is given the task of writing the class that carries out the checking and the calculations. Programmer B comes up with codes as shown in Listing 4.14.

1. public class Certification2. {3. int code;4. double cost;5. String s;6. static final double LIFE_INSURANCE = 250,

HEALTH_INSURANCE = 150,MORTGAGE = 350,APPRAISAL = 300,REGISTRATION = 50;

7. public Certification(int code)8. {9. this.code = code;10. cost = REGISTRATION;11. s = "";12. }

13. public void getCost()14. {15. switch(code)16. {17. case 1:18. cost = cost + LIFE_INSURANCE;19. s = s + "Life insurance ";20. case 2:21. cost = cost + HEALTH_INSURANCE;22. s = s + "Health insurance ";23. case 3:24. cost = cost + MORTGAGE;25. s = s + "Mortgage ";26. case 4:27. cost = cost + APPRAISAL;28. s = s + "Appraisal";29. break;30. default:31. s = “No such course is offered”;32. cost = 0;33. break;34. }

35. }36. public String toString() { return cost + " " + s; }37. }

Listing 4.14 the class Certification.

34

When the program is executed, the input dialog window shown in Figure 4.12 appears. The option is typed, in this case option 1. The program proceeds to carrying out the process. To the dismay of programmer B, the output was not what was expected. See Figure 4.13.

Figure 4.12 the input dialog window.

Figure 4.13 the incorrect result from the switch statement of the program.

Rules Governing the Switch Statement

Exercises 4b

35

The control expression or selector variable that follows the keyword switch must be an integer or an integer equivalence, except the data type long.

The expression, called case-label, that follows the keyword case must be a constant, and not a variable.

The case-label must be unique. That is, no two case-labels must ever evaluate to be the same value.

There can be no more than one default in a given switch statement

1. Pitfall I thru III show common errors make by beginning programmers. Re-write each pitfall so that each produces the desired result.

2. Given the following code:char m = ‘a’;switch(m){

case ‘a’:System.out.println(“a”);

break;default:

System.out.println(“default”);break;

}

What will happen when you attempt to compile and execute this code?(a) The code will not compile because the switch statement does not have a legal value.(b) The code will compile and run, but nothing will be printed on the screen.(c) The code will compile and run, and the letter a will be outputted on the screen.(d) The code will compile and run, and the letter m will be outputted on the screen(e) The code will compile and run, and the word default will be outputted on the

screen

3. Re-write each of the following program fragments using a switch statement.

(a) if (x == 1)y = x;

else if ( x == 2)y = x * x;

else if (x == 2 )y = x * x * x;

elsey = 0;

(b) Assume score is an integer variable between 0 an 10.

if (score > 9)grade = ‘A’;

else if(score > 8)grade = ‘B’;

else if(score > 7)grade = ‘C’;

else if(score > 5)

36

grade = ‘D’;else grade = ‘E’;

(c) if (ch == ‘a’ || ch == ‘b’ || ch == ‘c’){

if (ch == ‘a’) System.out.println(“You have an A”);

else if(ch == ‘b’)System.out.println(“You have a B”);

else System.out.println(“You have a C”);

}else if (ch > ‘c’ && ch < ‘e’)

System.out.println(“Your have a D”);else if(ch == ‘e’)

System.out.println(“Your have a D-”);else

System.out.println(“Your exam is ungradable”);

4. Study the following segment of code.

1. int j = 5;2. switch(j)3. {4. case 3 + 2:5. System.out.println(“The value is 5”);6. break;7. default:8. System.out.println(“The value is undeterminedj”);9. break;10. case 4:11. System.out.println(“The value is j”);12. break;13. }

What statements are true about this segment of code?

(a) The code is illegal because the arithmetic expression at Line 4.(b) The code will compile and run, and The value is 5 is printed on the screen.(c) The code will compile and run, and The value is undetermined is printed on the

screen.(d) The code will compile and run, and The value is j is printed on the screen(e) The default statement should come last in the series of case statement.

5. Design a class called TemperatureConversion. The class accepts two values, a character followed by a numeric quantity. The character represents one of the three conversions:

If the character is the letter C, convert the temperature given (the second value) from Fahrenheit to Centigrade. The formula for this conversion is C = 5/9(T – 32).

37

If the character is the letter F, convert the temperature from Centigrade to Fahrenheit. The formula is F = 9/5T + 32, and

If the character is K, convert the temperature from Centigrade to Kelvin. The formula is K = C + 273.16.

Use the switch statement in your solution to determine each conversion. Write a test class for the TemperatureConversion class

38

Iterative Statements

So far in our studies, we have discussed and have been using two forms of Java statements – sequence and selection. There is a third type of Java statement – the iterative statements, commonly called loops. Iterative statements cause a program to repeat certain statement or block of statements. The statement or block of statements is referred to as the loop body. You may be wondering how the program knows to execute the loop body repeatedly. The answer is, a conditional expression is used to determine if the loop is to continue to execute, or to terminate.

If you were asked to add all the integers from 1 to 1000 and the only method that you know was addition, you would more than likely write something like this:

1 + 1 = 22 + 1 = 33 + 1 = 44 + 1 = 55 + 1 = 6

:::

Surely it will not be long before you realize that this approach is repetitive and laborious. The concept, iteration, which is a fundamental tool to programming, relieves us from this drudgery. In likewise manner, the computer is capable of carrying out tasks on a repetitive basis.

Java provides three forms of iterative statements. These are the while statement, the do…while statement, and the for statement.

The while Statement

The format of the while statement is as follows:

while ( conditional_expression ) body;

Where the word while is the Java keyword indicating a repetitive construct. Within the pair of parentheses is a conditional expression that must be tested, in order to determine if the loop body must be executed again, and again, until a certain condition stops it.

39

The while statement specifies that the conditional expression must be tested at the beginning of the loop. If the conditional expression is initially false, then the loop body is skipped. Figure 4.14 shows a diagrammatical representation of the while loop.

false

true

Figure 4.14 symbolic representation of the while loop.

Example 4.8

Write a while loop that prints all the integers from 1 and 1000.

Solution

The solution to this problem focuses on two key issues - counting from 1 to 1000, and print the number. The solution is depicted in Figure 4.15.

false

true

40

Loop body (Usually includes updating the loop variable.

Program execution continues

counter <= 1000

Print the number Update counter: counter =

counter + 1

Program execution continues

counter = 1

conditional expression

Initialize the loop variable

Figure 4.12 a diagrammatic solution t the problem.

Listing 4.15 shows the solution in code form.

1. public class Integers2. public static void main(String[] arg)3. {4. int counter = 1;5. while (counter <=1000)6. {7. System.out.println(counter);8. counter = counter + 1;9. }10. }

Listing 4.15 using the while loop.

Line 4 declares and initializes the loop variable, counter. It is used as the basis for the conditional expression (counter <= 1000), in the while clause. See Line 5. The loop body is enclosed with the pair of curly braces, Lines 7 and 8 form the loop body.

In example 4.8 we were told the number of times that the loop must iterate. There are times however, when we do not know the number of times that the loop will iterate. In situations of the kind, we will have to set up the conditional expression so that the loop must terminate.

Example 4.9

Design a class that accepts an integer value and prints the digits of the number in reverse order. For example, if the number is 234, the program should print 431, or if the number is 24500, it should print 00542.

Analysis:

Based on the problem definition, we cannot tell in advance the number of digits contained in a given number. We must however, print the digits from the rightmost to the leftmost one. That is:

1. Given a number, say, N.2. The rightmost digit that is to be printed is determined by N%10. For example, if the number is 234, then

the rightmost digit to be printed is 234%10, which is 4.3. The next rightmost digit in N is determined by N/10. Using the example 234, the next rightmost digit is

234/10 which is the number 23. This is N.4. Steps 2 and 3 are repeated until the new value in N is zero.

For instance, let N = 234, then the process works this way:

41

N Process Digit printed234 234%10 423 234/1023 23%10 32 23/102 2%10 20 2/10

Listing 4.16 shows the class ReverseNumber. It is a translation of the algorithm worked out above.

1. public class ReverseNumber2. {3. private int N;4. private String s;

5. public ReverseNumber(int N)6. {7. this.N = N;8. s = "";9. }

10. void reverse()11. {12.while (N > 0)13.{14.s = s + N%10;15.N = N/10;16.}17. }

18. public String toString() { return s; }19. }

Listing 4.16 shows how the digits in a given integer can be reversed.

The constructor accepts an arbitrary integer N. The method reverse(), shown on Lines 10 – 17 shows the process by which the digits are reversed. The while clause shows the conditional expression which governs the loop body – Lines 14 and 15. As long as the conditional expression is evaluate to true, the loop continues to iterate. The iteration stops when N becomes zero. Note: instead of printing the digits immediately after generating them, they are appended by the string variable s, Line 15.

Listing 4.17 shows a typical test class that utilizes the class ReverseNumber.

42

1. public class TestReverseNumber2. {3. public static void main(String[] arg)4. {5. ReversingNumber r = new ReversingNumber(24500);6. r.reverse();7. System.out.println(r);8. }9. }

Listing 4.17 Test class for the class ReverseNumber.

Sometimes the conditional expression stated in the problem is less intuitive than what we have seen in the previous section. When such situations arise, there is a high degree that two or more relational expressions are involved. If you are faced with situations of this kind, design a Boolean method solely to formulate and test the condition under which the loop will operate.

Example 4.10

The XYZ School wants to carry its grade 10 students on a trip. The cost of the trip is $5,000.00. The school has only thirty days in which to collect the funds in order to go on the trip.

Design a class called SchoolContribution that creates a contribution account. Incorporate the following: A method called totalContribution(..) that accepts and accumulates

the daily contributions. A Boolean method called hasMoreTime() that determines if more time

is needed to reach the targeted amount. A Boolean method called hasNotMadeTarget() that determines if more

contribution is needed. A Boolean method called metTarget() that reports if target has been

met.

Write a test class called TestContribution that generates the daily contributions. It keeps making contribution until it determines that either the targeted amount of contribution is met or the time allotted to collecting the amount of money expires. In either case it displays the amount of money collected each day, and the accumulated amount.

Analysis:

The class SchoolContribution has:

Constants

43

o TARGET - the amount of money to be made - $5000.00o MAX_DAYS - number of days in which to meet target – 30

Variableso day - the day that contribution is made.o totalContribution – the amount collected at the close of each day.

Constructoro The initial amount of money collected is zero.

Methodso addContribution – accepts a contribution, adds it to total contribution, and updates the count for

number of days.o Boolean methods - hasMoreTime() and hasNotMadeTarget() allow the loop to continue

if target is not met within the 30 days. That is, the target is not met if the amount collected is below the targeted amount and the number of days is less than 30. The following conditional expressions represents each of the methods, respectively.

day <= MAX_DAYS and totalAmount < TARGET

o Boolean method metTarget() – tells us if the target was met. That is, after 30 days, was the target met. This is answered by the following conditional expression.

day >= MAX_DAYS && totalContribution < TARGET

This is less obvious, but it is necessary to know, in order to print the output.

Listing 4.18 shows the definition for the class SchoolContribution.

1. import java.text.NumberFormat;

2. public class SchoolContribution3. {4. static final byte DAYS = 30;5. static final float TARGET = 5000;

6. int day;7. double totalContribution;8. String s;9. NumberFormat df;

10. public SchoolContribution()11. {12. totalContribution = 0;13. day = 0;14. s = "Day \tDaily Contribution\tTotal Contribution\n";15. df = NumberFormat.getCurrencyInstance();16. }

44

17. public void addContribution(double amount)18. {19. totalContribution = totalContribution + amount;20. day = day + 1;21. s = s + day + "\t " + df.format(amount);22. s = s + "\t\t " + df.format(totalContribution) + "\n";23. }

24. public boolean hasNotMadeTarget () 25. {26. return totalContribution < TARGET;27. }28. public boolean hasMoreTime()29. {30. return day < MAX_DAYS;31. }32. public boolean metTarget ()33. {34. return day <= MAX_DAYS && totalContribution > TARGET;35. }36. public String toString() { return s; }37. }

Listing 4.18 the class SchoolContribution

To summarize, this class simply does the following:

It accepts the daily amounts, accumulates the contributions, and updates the day count. These activities are shown the method addContribution(…).

Determines the conditional expression for the loop as seen in the method didNotMakeTarget(). Determines whether or not the target was made. See the method isInadequate().

Listing 4.19 shows the code for the test class, TestContribution. The class does the following:

Creates an empty contribution account. Continuously check if the target has been met. It uses the result from the method didNotMakeTarget()

to control the loop after a day’s contribution has been made. Prints the result after the loop is exited. The if statement on Line 12 uses the result from the Boolean

method isInadequate() to print the result.

1. import javax.swing.JOptionPane;2. public class TestContribution3. {

45

4. public static void main(String[] arg)5. {6. SchoolContribution s = new SchoolContribution();7. while (s. hasNotMadeTarget() && s.hasMoreTime())8. {9. s.addContribution(Double.parseDouble(10.JOptionPane.showInputDialog("Make contribution")));11.}

12. if (s. metTarget ())

System.out.println(s);elseSystem.out.println("We did not make the target" +

"\nSorry we cannot go on the trip\n" + s);13. }14. }

Listing 4. 19 the test class TestContribution.

In Listing 4.19, the while statement monitors the loop body. It calls the methods hasNotMadeTarget() and hasMoreTime() to tell if the loop must continue.

Nested while Loop

The while statement like the if statement, can be nested. Recall that the format of the while statement is:

while (condition)S;

Where S represents a Java statement. If this is the case, then S itself can be a while statement. The construct would therefore be:

while (condition1)while (condition2)

S;

Figure 4.xx shows a diagrammatic representation of one while loop that is nested within another.

46

falseconditional_1

true

falseconditional_2

true

This diagram is interpreted as follows – if condition 1 is true, then the inner part of the diagram is executed; but the execution contains another condition. That is, what follows condition1 represents the outer loop body. This loop body constitutes condition2. If this condition is true, then what follows is the inner loop body. This loop repeats until condition 2 is false, at which time execution returns to the outer loop. The outer loop continues until condition1 is false, at which time the entire loop terminates.

Example 4.xx

A company has five stores – A, B, C, D, and E – at different locations across the state of Florida. At the end of each week the company’s management prints a report of the daily sales and the total sales for each of the stores.

47

Initialize outer loop

Initialize inner loop

Inner loop body Update inner loop variable

Update outer loop variable

Program exits loops

Write a class called Sales that prints the sales and the total sales for each of the stores, row by row.

1. import javax.swing.JOptionPane;2. import java.text.NumberFormat;3. public class Sales4. {5. private double totalSales;6. private static final int DAYS = 7;7. private static final char STORES = 'E';8. private String header;9. private String s;10. private static final NumberFormat nf= NumberFormat.getCurrencyInstance();11. public Sales()12. {13. totalSales = 0;14. s = "";15. header = "Store\t\t\tDay\n" +16. "\t1\t2\t3\t4\t5\t6\t7\tTotal\n";17. }18. public void getSales()19. {20. char store = 'A';21. while (store <= STORES)22. {23. s = s + store + " - ";24. int day = 1;25. totalSales = 0;26. while (day <= DAYS)27. {28. double amount = Double.parseDouble(JOptionPane.showInputDialog(

"Store " + store + "\nDay " + day + "\nEnter amount"));29. s = s + "\t" + nf.format(amount);30. day++;31. totalSales = totalSales + amount;32. }33. s = s + "\t" + nf.format(totalSales) + "\n";34. store++;35. }36. }37. public String toString()38. }39. return header + s;40. }41. }

48

1. import javax.swing.JOptionPane;2. import javax.swing.JScrollPane;3. import javax.swing.JTextArea;4.5. public class TestSales6. {7. public static void main(String[] arg)8. {9. Sales s = new Sales();10. s.getSales();11. JTextArea t = new JTextArea(s.toString(), 8, 50);12. JScrollPane p = new JScrollPane(t);13. JOptionPane.showMessageDialog(null, p, "Weekly Sales",

JOptionPane.INFORMATION_MESSAGE 14. );}15. }

49

As we have seen, there are problems that require nested looping construct in their solution. However, some of those problems do not explicitly say so, nor do they make any indication of the use of a loop. It is therefore left to the experience of the programmer to recognize that looping construct is required, what the conditional expression for the loop will be, and how it will be implemented.

Example 4.12

Write a program that makes mailing labels. Assume that the information is gathered line by line. That is, given the name and address as one line of text, the program should write the name of the person on the first line, the street on the second line, city on the third line, and so on. For example given the line of information:

John Brown, 3300 Spanish Moss Terrace, Apt # 240, Lauderhill, Fl 33319

The program should output:

John Brown3500 Spanish Moss TerraceApt # 240LauderhillFl 33319

In this problem we want to design a class that basically does the following:

Accepts a string value. Decomposes or parses the string into separate units. Each unit is commonly called a token. Extracts each token and prints each on a separate line.

In order to decompose a string into tokens, Java provides a class called StringTokenizer for this purpose. Two of its most frequently used constructors are:

StringTokenizer(String s) This constructor parses a string into tokes by using default delimiters. These default delimiters are: the space character, the tab character, the new line character, the carriage-return character, and the form-feed character.

StringTokenizer(String s, String delimiter) This constructor parse a string according to the delimiter specified. The delimiter itself is not part of any of the tokens.

The second constructor is more applicable in this problem, because we can use the comma character as the delimiter between tokens. Three of the more frequently used methods in this class are:

boolean hasMoreTokens() This method tests if there are more tokens available in the string.

String nextToken() This method returns the next available token from the string.

50

String nextToken(String delimiter) This method uses the argument given to set a new default delimiter. It then returns the next available token.

countTokens() This method returns a count of the number of tokens in the string.

The class StringTokenizer is found in the java.util package. It must be imported.

Now that we have the requisite tools, we can move on to solving the problem. Let us do the following:

1. Name the class that makes the mailing labels MailingLabels.

2. Define a method called makeLabels(…) that accepts string values, one at a time and tokenizes each. Figure 4.13 shows how the method will loop through a tokenized string to get the next available token.

Listing 4.20 shows the code for the class MailingLabels.

false

true

Figure 4.13 shows how the while loop will be used to get a get a token.

Listing 4.20 implements the flow diagram shown in Figure 4.13.

1. import java.util.StringTokenizer;

2. public class MailingLabels3. {4. String s;

5. MailingLabels() { s = ""; }

51

Tokenize string

hasMoreTokens()

Get nextToken() and process it

Next statement

6. void makeLabels(String str)7. {8. String token = "";9. StringTokenizer t = new StringTokenizer(str, ",");

10.while (t.hasMoreTokens())11.{12.token = t.nextToken();13.token = token.trim();14.s = s + token + "\n";15.}16.s = s + "\n\n";17.}

18. public String toString() { return s; }19. }

Listing 4.20 the code for the class MailingLabels.

The focus in this class is how the while construct makes use of the StringTokenizer class. First of all, in order to use the StringTokenizer class, it has to be imported, as seen in Listing 4.20, Line 1. The method makeLabels is the next key issue. This class accepts a string value. See the method header, Line 6. Line 9 thru Line 16 is a translation of Figure 4.13. First the string is tokenized, using the comma as the delimiter. See Line 9. Next the Boolean method hasMoreTokens() checks to see if there is another token in the tokenized string. See Line 10. If there is another token, it processes it; if there is no more, then the loop body is skipped, and control passes to Line 16. Also, notice the loop body: Line 12 fetches the next available token; Line 13 trims any blank that may be to the left or to the right of the string; and Line 14 simply concatenates this new token and the new line character to the existing output string, s.

Listing 4.21 show a typical test class for the class MailingLabels.

1. import javax.swing.JOptionPane;

2. public class TestMailingLabels3. {4. public static void main(String[] arg)5. {6. MailingLabels m = new MailingLabels();

7. String s = JOptionPane.showInputDialog("Enter name and address");

8. while (!s.equals(""))9. {10.m.makeLabels(s);

52

11.s = JOptionPane.showInputDialog("Enter name and address");12.}13. System.out.println(m);14. }15. }

Listing 4.21 test class TestMailingLabels.

The focus in this class is the use of the while loop again. Because we do not know in advance how many mailing labels there will be, we use the while loop to determine this. That is, the loop will continue to execute as long as the JOptionPane does not return a blank string. See Line 8 in Listing 4.21.

Still there are other types of problems that give some indications of iteration through formulae or through patterns. Problems that fall in this category usually require some Mathematical skills and analytical skills to solve them.

Example 4.13

The value of π can be determined by the series equation:

π = 4 ( 1 – 1/3 + 1/5 – 1/7 + 1/9 – 1/11 + 1/13 - ….)Write a class called PI that finds an approximation to the value of π to 8 decimal places.

Write a test class called TestPI that displays the value of π and the number of iterations used to find this approximation.

Analysis

Each term is the series is generated as follows:x1 = -1/(2 * 1 + 1)x2 = 1/(2 * 2 + 1)x3 = -1/(2 * 3 + 1)

::

In general the ith term is: xi = (-1)i/(2i + 1)

This type of problem requires you to compare the absolute value of the difference of two successive terms. If the value is less that the threshold or margin of error, then the new value generated is the approximation to the actual value. In other words,

while ( |xnew – xold| > some margin of error){

sum the new value to previous amountsave the new as old.generate the new value, xnew.

}

53

In this example the margin of error is 0.00000005. In addition, each new term may be generated as follows expression:

xn = Math.pow(-1.0, n)/(2 * n + 1);

Listing 4.22 shows the class PI.

1. import java.text.NumberFormat;2. import java.text.DecimalFormat;

3. public class PI4. {5. static final double MARGIN_OF_ERROR = 0.00000005;6. double sum;7. int iterate;

8. public PI() { sum = 1; }

9. public double findXnew(int n) 10. { 11. return Math.pow(-1.0, n)/(2 * n + 1); 12. }

13. public void findPi()14. {15. int i = 1;16. double xold = 1.0;17. double xnew = findXnew(i);

18.while (Math.abs(xnew - xold) > MARGIN_OF_ERROR)19.{20.sum = sum + xnew;21.xold = xnew;22.i++;23.xnew = findXnew(i);24.}25. iterate = i;26. }

27. public String toString()28. {29. NumberFormat nf = NumberFormat.getInstance();30. DecimalFormat df = (DecimalFormat)nf;31. df.applyPattern("0.00000000");

54

32. return "The approximate value of pi is " + df.format((4*sum)) + "\n" +"The number of iterations is " + iterate;

33. }34. }

Listing 4.22 the class PI.

The test class shown in Listing 4.23 simply creates a PI object, calls the method findPi, and then prints the result.

1. public class TestPI2. {3. public static void main(String[] arg)4. {5. PI p = new PI();6. p.findPi();7. System.out.println(p);8. }9. }

Listing 4.23 the test class TestPI.

Exercises 4c

1. Study the following programs and write down what will appear on the screen you compile and execute them.

(a) public class Mystry{

public static void main(String[] arg){

int k = 1;while (k <= 10){

System.out.println(k);k++;

}}

}

(b) public class Mystry{

public static void main(String[] arg){

55

int k = 2;while ( 27%k <= 6){

System.out.println(k + “ “ + 27%k);k++

}}

}

(c) public class Mystry{

public static void main(String[] arg){

int m= 2, n = 50;while ( m < n ){

m = n * 3;System.out.println(m+ “ “ + n);

}}

}

(d) public class DoubleLoop{public static void main(String[] arg){

int i = 4;while (i >= 1){

System.out.print(i); int j = 3; while (j >= 1) {

System.out.println("\t" + j);j--;

} System.out.println("---------"); i--;}

}}

56

2. Write a class called TestScores. For any given student the initial score is 0. Write a method called addScores that accepts the score for each individual and sums them. Also, write a method called avergarScore that calculates and return the average score for each student.

Write a test class called TestScores. This class uses the JOptionPane input dialog window to read each score. The first number read, represents the number of scores for each student. This is followed by the actual scores.

3. Write a class called Numbers to find the minimum of a sequence of nonnegative numbers. The class is supplied the numbers one by one. Write a method called findMinimum to determine the number that is the least. Provide methods to return the numbers in the order that they were read, the number of entries, and the number which is the least in the sequence. The value that terminates the process must not be printed.

Write a test class that generates the numbers. When a negative number is entered, the process stops, and the output is generated. For example, given the following input values 120 250 450 50 200 100 75 -10, the program should generate an output similar to the following.

4. Modify Exercise 3 to incorporate a method to find the largest number in the sequence. The program should generate out similar to the following.

5. Write a Java program that can be used to produce patterns of the following form:

57

The do…while Statement

The do …while statement is opposite in a way to the while statement, in that the conditional expression comes after the loop body. The format of the do … while statement is:

do {

statement;}while (condition ) ;

Where the word do is the keyword, indication the beginning of the do..while loop. The pair of curly braces is mandatory, even if the loop body is a single statement. The statement finishes with the while clause. Notice that the conditional expression is enclosed within parentheses. In addition, the entire statement must terminate with a semi-colon.

true

false

Figure 4.13 a symbolic representation of the do…while loop.

Figure 4.13 is representing the construct of the do..while loop. The do..while loop must be used with caution, since it is attempting to execute the loop body without knowing if it is possible. For instance, consider the following segment of code:

int i = 1;do

58

conditional_expression

statement

Loop body

{System.out.println( i/(i-1) );

}while(i !=0);

Although the code is syntactically correct, it fails to execute. You may ask why it did not execute when there is a conditional expression that should take care of the error. Line 4 indeed carried out the test for division by zero, but this test comes too late, the division in Line 4 has been attempted already. In general, it is not guaranteed that the execution of the loop body will ever be completed at all, upon a first attempt at executing it. If you intend to use this looping construct, your code should guarantee that execution of the loop body will terminate normally.

The following program segment creates a string, and then uses the do..while loop to print each character in the string.

int i = 0;String s = new String("Hello");do {

System.out.println(s.charAt(i));i = i + 1;

}while(i < s.length());

This code by itself works fine. However, let us construct a class called DoWhile that incorporates this segment of code in a method called doFirst(). The class definition is shown in Listing 4.24.

1. public class DoWhile2. {3. private String s;

4. public DoWhile(String s)5. {6. this.s = s;7. }

8. public void doFirst()9. {10. int i = 0;11.do12.{13.System.out.println(s.charAt(i));14.i = i + 1;15.}while(i < s.length());16. }17. }

59

Listing 4.24 use of the do while statement to print the individual characters of the string.

As we said before, if you intend to use the do..while statement you must ensure that the loop body will execute without flaw. In Listing 4.24 the program fails, if the class gets an empty string. That is the clause s.charAt(i) fails, because charAt(0) would not have existed. This problem is fixed by checking if the string is empty. This can be done in one of two ways, namely, check:

1. !s.equals(“”), or

2. s.length() > 0

The for Statement

The for statement, like the while and the do..while statements, is a looping construct that continually executes a section of code, if a given condition is true. When the condition becomes false the section of code is skipped, and the next statement following it is executed. The general format of the for statement is as follows:

for ( data_type id = initialValue; conditional_expression; adjust_id )statements;

The for loop is a single executable statement consisting of two major parts – loop heading, following the keyword for, and the loop body. The loop heading is enclosed within the pair of parentheses and consists of three parts, each separated from the other by a semi-colon.

The first expression - data_type id = initial - constitutes the declaration and initialization of the control variable for the loop.

The second expression - conditional_expression - constitutes the condition under which the loop iterates. Any valid conditional expression is acceptable.

The third expression - adjust_id – updates the value of the loop variable.

The loop body constitutes the statement or statement block to be executed. The loop body executes only if the conditional expression is true, other than that the for loop terminates. Figure 4.14 shows a diagram of the for loop.

true

60

condition

data_type id = initial

adjust_idLoop body

false

Figure 4.13 a representation of the for loop.

The for statement behaves the following way:

1. First, the control loop variable is declared and initialized.2. Second, the condition is tested. If the condition is true, the loop body is executed, if not, it terminates.3. Third, the loop variable is updated. That is, the control variable is re-assigned, and step 2 is repeated.

Example 4.12

Write a program that lists the integers from 1 to 10, along with their squares and their cubes. That is, the program produces:

1 1 12 4 83 9 27

::

Let us represent the solution using a flow diagram, as shown in Figure 4.14.

true

false

Figure 4.14 for loop representation

Listing 4.25 shows a translation of Figure 4.14.

1. public class Powers2. {

61

statement

i<= 10

int i = 1

…….

i++Print N, N*N, N*N*N

3. public static void main(String[] arg)4. {5. System.out.println("N\tN*N\tN*N*N");

6. for (int i = 1; i <= 10; i++)System.out.println(i + "\t" + i*i + "\t" + i*i*i);

7. }8. }

Listing 4.25 using the for loop construct

The problem focuses on the use of the for loop. Listing Line 6 shows its usage.

The control loop variable is represented by the clause: int i = 1; The conditional expression is represented by by the clause: i <= 10; The adjustment on the loop variable is represented by the clause: i++, and The loop body is represented by: System.out.println(i + "\t" + i*i + "\t" + i*i*i);

Figure 4.26 shows the output.

Figure 4.26 N, N2 and N3.

Like the while loop, there are some problems that do not explicitly state the conditional expression for the loop.

Example 4.13

Write a class that accepts a string value and places a pound sign (#) character between successive letters. For example, given the word ASSIGNMENT the program would print A#S#S#I#G#N#M#E#N#T as the output.

Solution

62

Let us call the class Word. Principal variable is the string variable containing the value. Principal method must address the following:

(a) The number of characters in the string. This can be determined by the method length(), from the class, String.

(b) Declare and initial the index variable, say i. In this case it begins at 0, since the index of a string begins at 0. That is, this clause takes the form: int i = 0;

(c) The conditional expression that controls the loop. In this case the index variable say, i < length().

(d) Update the loop variable. In this case i++.(e) Define a new string variable such that after each character is encountered, a pound sign (#) is placed

to the right of that character in the string except for the last character.

Listing 4.26 shows the code for this problem.

1. public class Word2. {3. private String aWord;4. private int index;

5. public Word(String s)6. {7. aWord = s;8. index = s.length();9. }10. public String toString()11. {12. String s = "";13.for (int i = 0; i < index; i++)14.{15.s = s + aWord.charAt(i);16.if (i != index - 1)17.s = s + "#";18.}19. return s;20. }21. }

Listing 4.26 using the for loop to traverse a string.

In Listing 4.26 focus centers around the for loop construct in the toString() method. Although the problem did not suggest in any way looping, when we analyzed the problem, we discovered that it was necessary to access each

63

character in the string serially. Furthermore, we knew the position of the first and last position in the string. This makes for easy traversal of the string, using the for loop, seen in Line 13.

The test class, Listing 4.27,simply creates a Word object with the string ASSIGNMENT.

1. public class TestWord2. {3. public static void main(String[] arg)4. {5. Word w = new Word("ASSIGNMENT");6. System.out.println(w);7. }8. }

Listing 4.27 class TestWord.

Example 4.14

A palindrome is a set of data values that is identical to its reverse. For example the word MADAM is a palindrome; the number 123454321 is a palindrome; likewise aaabbaaaabbaaa. Design a class called Palindrome that accepts a string and determines if the string is a palindrome.

To determine if a sequence of characters is a palindrome do the following: Compare the first and last character in the sequence. If the are the same, Compare the second character and the second to the last character in the sequence. Continue the process in similar manner. If all items match, then the string is a palindrome. Conversely, at the first mismatch occurrence, then the string is not a palindrome.

1. public class Palindrome2. {3. private String word;4. private boolean palindrome;5. private int index, halfIndex;

6. public Palindrome(String s)7. {8. word = s;9. index = s.length();10. palindrome = true;11. halfIndex = index/2;12. }

13. boolean isPalindrome()14. {15. for (int i = 0; i < halfIndex && palindrome; i++)

64

16. if (word.charAt(i) != word.charAt(index - i - 1))17. palindrome = false;18. return palindrome;19. } 20. }

Listing 4.27 class Palindrome accepts the string and check if it is a palindrome.

In Listing 4.27 we assume that the string is a palindrome, by using the Boolean variable palindrome = true. See Line 10. Instead of traversing the entire string in one direction, we half the index so that we can compare values at the corresponding ends as described above. If any two characters at corresponding ends are not the same then the variable palindrome is set to false and the for loop terminates. As we said earlier, the conditional expression in a for loop can be any valid Boolean expression. For instance, the conditional expression for this for loop is a logical expression - i < halfIndex && palindrome .

The test class Listing 4.28 creates a Palindrome object with the string aaabbaaaabbaaa.

1. public class TestPalindrome2. {3. public static void main(String[] arg)4. {5. Palindrome p = new Palindrome("aaabbaaaabbaaa");6. System.out.println(p.isPalindrome());7. }8. }

Listing 4.28 Test class TestPalindrome

Nesting for Loops.

The for loop may be nested. The depth of nesting will depend on the application. Let’s say we want to write a class that prints the twelve times table or any of the tables, we could use two for loops for this purpose.

Example 4.15

Design a class that prints any timetable.

65

1. import java.util.Scanner;

2. public class NestedFor3. {4. public static void main(String[] arg)5. {6. System.out.println("Enter number for time table");

7. Scanner read = Scanner.create(System.in);8. int N = read.nextInt();

9. String s = "\n x";

10. for (int i = 1; i <= N; i++)11. s = s + "\t" + i;

12. s = s + "\n";

13. for (int k = 1; k <= 12; k++)14. {15. s = s + k;

16. for (int l = 1; l <= N; l++)17. s = s + "\t" + (l*k);

18. s = s + "\n"; 19. }

20. System.out.println(s); 21. }22. }

Scope of a Loop control variable

In general, the loop control variable must be must be declared before it is used in the loop. The scope of this variable will be in the program block in which it is declared. However, it is advisable that this variable does not extend beyond the header of the for loop. If it is extended beyond the header the program could suffer from serious side effects, such as the variable picking up values outside the limiting value of the conditional expression. The loop

66

control variable can be used inside the loop body just like any other variable. However, the variable should not be modified by the loop body. This too can cause serious side effects.

PitFall

It is absolutely essential that a for loop be written in such a way that the conditional expression will eventually evaluate to false. If not, the for loop will never terminate; this is called an infinite loop. If your program appears to hang, check the for loop to make sure this didn't occur.

Here is an example

Pitfall I – Updating the loop variable incorrectly

1. public class PitFall_I2. {3. public static void main(String[] arg)4. {5. for (int i = 10; i > 1; i++)6. System.out.println("The value of i is " + i);7. }8. }

Pitfall II – Modifying the loop variable in loop body

The control variable is local to the for statement. It is recommended that you do not change the value of the loop control variable within the body of the for statement. To do so could cause the program to produce incorrect results.

1. public class PitFall_II2. {3. public static void main(String[] arg)4. {5. for (int i = 1; i < 10; i++)6. {7. System.out.println(i*i);8. i = i + 5;9. }10. }11. }

67

Exercises 4d

1. Write a class to create the letters as shown below. Write separate class method for each letter. (Hint – use for loops).

For example the letter L was form by the code in the method makeL():

public class Letter{

static String s = "";

static String makeL(){

s = "\n";for (int i =1; i < 10; i++)

s = s + "ll" + "\n";

for (int k =1; k < 7; k++)s = s + "ll" ;

68

s = s +"\n";for (int k =1; k < 7; k++)

s = s + "ll" ;return s + "\n";

}::

}

Note – you will need a test class to run this class.

69

Summary

The statements in a program will execute in a linear fashion unless they are directed otherwise.

The control structures called selection and iteration are used to alter the order in which statements are executed.

The selection construct has two forms, namely, the if statement and the switch statement.

The if statement simply determines if a statement or statement block must be executed. The decision is based on the outcome of a Boolean expression.

The if..else statement determines what statement must be executed from a series of choices.

The if and if..else statements may be nested.

The switch statement is a special form of the if..else statement.

The switch statement can only test byte, short, int, and char data types.

The case labels must be unique. They cannot be represented by variables. They must either be literals or they may be represented by constants.

The default statement is optional.

Iterative statements – while, do..while and for – cause a program to repeat certain sections of programs called the loop body.

A loop body, whether a single statement or a block of statements, gets repeated based on some conditional expression.

The while statement specifies the conditional expression before the loop body is specified. If the conditional expression is false initially, then the loop body is skipped. If it is false after the loop body has been entered, then the loop is not repeated again, but is terminated.

The do..while statement specifies the conditional expression after the loop body – hopefully – has been executed.

70

Exercises

2. A wholesale company discounts the price of its products depending on the number of units bought and the unit price per for each item. The rules for calculating discounts are shown in the table below.

Unit Price

Quantity 0 - $10.00 $10.01 - $20.00 $20.01 & over

1- 49 0% 1% 2%

50 - 99 1% 2% 3%

100 & over 2% 5% 10%

To solve this problem do the following:i. Use the class GetData from assignment 4 to read the data from the keyboard.

ii. Write a class called Discount that accepts the number of units and the corresponding price. It validates the quantities and calculates the discount amount where possible. Redefine the method toString to format the output.

NOTE: DO NOT USE ANY LOGICAL OPERATIONS IN THIS EXERCISE.

iii. Write a test class called TestDiscount that uses the data given below to test class Discount.

iv. Write a class called Report that accepts a string object. The class simply displays the result in a scrolling JOptionPane window.

Use the following test data.Quantity Unit Price10 $15.00

-10 $5.00 50 - $10.00

200 $25.0080 $50.0010 $20.00

The output must be of the form:

The quantity is: xx The unit price is: $xx.xx The discount is: $xx.xxOrThe quantity is: -xx Quantity is negative. Cannot compute discountOrThe quantity is: 150 The unit price is: -$15.00 The money is negative, cannot compute discount amount

71

2. The Fast Freight Shipping Co. charges the following rate for shipping customer's package. Weight of Package (in Kilograms) Rate 2 Kg or less $1.10 Over 2 Kg but no more than 6 Kg $2.20 Over 6 Kg but no more than 10 Kg $3.70 Over 10 Kg but no more than 20 Kg $4.80 20 Kg or more cannot be accommodated

3. After a year in the business the company modifies its charges on sending packages. In addition to the rules above, the company charges not only by weight, but also by distance. It does not ship packages at distance less than 10 miles, nor does it ship package over 3000 miles. The rate table now reads. Weight of Package (in Kilograms) Rate Per 500 Miles Shipped

2 Kg or less $1.10 Over 2 Kg but no more than 6 Kg $2.20 Over 6 Kg but no more than 10 Kg $3.70 Over 10 Kg but no more than 20 Kg $4.80 20 Kg or more cannot be accommodated

Write a class called Freight that will determine the charges per customer. The class must consider the following: whether the package is over weight, or not.

4. //Given the following code:

class TheSwitch{

public static void main(String []arg){

for (char i = 'a'; i < 'd'; i++) switch(i){

default: System.out.println("default");

break;case 'b': case 'a':

System.out.print(i + " "); break;

}}

}

What will happen if you attempt to compile and execute the code?(a) The code will not compile because the default statement should come last.

72

(b) The code will compile because character type cannot be used for a loop variable.(c) The code will compile and print the following on one line: a b default(d) The code will not compile since the for statement does not have a pair of curly braces.

5. Write a class called SalaryCalculator which computes the weekly salary for an employee. The class accepts the name of the employee and the number of hours worked. The employee gets $7.50 per hour for the first forty hours, and $11.25 per hour for each additional hour. In addition, the salary can only be calculated if the number of hours is between 0 and 80.

Write a class called TestSalaryCalculator. Use the following data to test your program:

John 40Harry 85Mary 65James -40

6. Write a class called convertTemperature that can be used to convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius. In this class the constructor accepts a value representing a temperature. Provide methods to carry out the conversions.

Use the JOptionPane class to write a menu driven test class. First the JOptionPane to enter the number that you want to convert. Secondly, use the JOptionPane again to select the method you want to call. Use the switch statement to determine which one of the methods is to be called. Here is the format of the menu:

Converting Temperature1. Celsius to Centigrade2. Centigrade to Celsius3. Quit

Use the following data to test your program:45 Celsius to Fahrenheit100 Fahrenheit to Celsius

1. This exercise will involve using: modulus operation, integer division, use of the switch statement, and the if, if-else statements.

The sign at a popular parking lot is as follows:

Popular Parking LotCars:First 1hours FreeThe next 5 hours $1.50/hourThe next 5 hours $1.25/hourOver 11 hours Flat fee of $20.00

73

Trucks:First 1 hour FreeUp to the next 5 hours $1.75/hourUp to the next 5 hours $1.50/hourOver 11 hours Flat fee of $25.00

Senior citizens in any case are charged a flat fee of $2.50.

To solve this problem do the following:i. Use the class called GetData to read the data from the keyboard.

ii. Write a class called Parking that accepts as input a single character designator (C, T, or S - which may be upper case or lower case), followed by the number of minutes a vehicle has been in the lot. The class computes the appropriate charge for each customer. Any fractional part of an hour must be counted as a full hour.

iii. Write a class called Report that outputs the ticket for each customer.

iv. Write a driver class called TestParking that uses the data given below to test class Parking.

Test Data

C 45C 125T 35S 65T 950

(Use the character designator in a switch statement to determine the vehicle type).

The output must be of the form for each customer:

Popular ParkingVehicle Minutes Hours Minutes Hours (Rounded) Costxxxx xx x xx x $x.xx

Example:Popular ParkingVehicle Minutes Hours Minutes Hours (Rounded) CostTruck 950 15 50 16 $25.00

74

7. The Babylonians had a simple method that they used to find the nth root of a positive number.

Given that x2 = a, find an approximate value of x such that x = √a. The Babylonian algorithm is as follows:

xi+1 = ½(xn + a/xn)

Use this method to find one root of x to 8 decimal places. Test your code with a = 100, and the initial guess

= 2;

8. The value of the exponential constant e can be determined by the Maclaurin series: ex = 1 + x + x 2 + x 3 + x 4 + x 5 + …. When x = 1, we get:

1! 2! 3! 4! 5!

When x = 1, we get:

e = 1 + 1 + 1 + 1 + 1 + 1 + ..… 1! 2! 3! 4! 5!

Write a class called ExponentialConstant to estimate e to 8 decimal places.

Write a test class called Test ExponentialConstant that displays the value of e and the number of iterations used to find this approximation.

9. Write a class called WindSpeedReadings. The class accepts wind speed readings (double) and determines the lowest, highest, and average wind speed readings.

Write a test class that creates a WindSpeedReadings object; also it must use the JOptionPane class to enter a series of readings from the keyboard in order for the WindSpeedReadings class to determine the lowest, highest, and average readings. The test class stops reading values from the keyboard when a negative is entered, and then prints: the individual readings, the highest reading, the lowest reading, the number of readings, and the average reading. The list must not include the negative value; the negative value must not be averaged neither.The JOptionPane input dialog would repeatedly display this format for input:

Typical output is as follows:

75

(Hint, use the while loop to detect when to stop reading values).

10. Write a class called depreciation to compute the depreciation schedules of an asset. Use the two accounting methods:

The straight-line depreciation method, and The sum-of-digits method of depreciation.

The algorithm for the straight-line method is simple; the amount to be depreciated is divided evenly over the specified number of years. Suppose that you have an asset of original value of $1,000.00 to be depreciated over 3 years. For example, the following table shows the depreciation and book value of the asset.

YEAR DEPRECIATION DEPRECIATION ACCUMULATED ASSET RATE AMOUNT DEPRECIATION VALUE

1 1/3 333.33 333.33 666.672 1/3 333.33 666.67 333.333 1/3 333.33 1000.00 0.00

The sum-of-the-digits work as follows: Suppose that you have an asset of original value $1,000.00 to be depreciated over 3 years. For example, the following table shows the depreciation and book value of the asset.

YEAR DEPRECIATION DEPRECIATION ACCUMULATED ASSET RATE AMOUNT DEPRECIATION VALUE

1 3/6 500 .00 500.00 500.002 2/6 333.33 833.33 166.673 1/6 166.67 1000.00 0.00

Your program must have the following:

showMenu: that displays the following menu when called:

1 - Straight Line 2 - Sum of Years Digits

76

0 – Quit

displayHeader: displays the table's headers straightLine : displays the straight line method table with appropriate values based on the given

asset. sumOfDigits : displays the sum-of-digits method table with appropriate values based on the given

asset.

Write a driver class called TestDepreciation. Use the following data to test the class depreciation.

Test your program with the following set of data; Amount: $10000.0 years: 10 method: straight line Amount: $20000.0 years: 10 method: sum of digits

77