iterative statements - school of computing and …smithjo/classnotes_2xxxx/... · web viewwrite a...

44
ITERATIVE STATEMENTS .......................................................... 1 The while Statement .......................................................... 2 Nested while Loop .................................................... 10 The do…while Statement ..................................................... 22 The for Statement .......................................................... 25 Nesting for Loops. ................................................... 31 Scope of a Loop control variable ..................................... 32 PitFall .............................................................. 32 Pitfall I – Updating the loop variable incorrectly ............... 33 Pitfall II – Modifying the loop variable in loop body ............ 33 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 = 2 2 + 1 = 3 3 + 1 = 4 4 + 1 = 5 5 + 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.

Upload: trinhliem

Post on 05-May-2018

216 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

ITERATIVE STATEMENTS ............................................................................................................................................ 1 The while Statement .............................................................................................................................................. 2

Nested while Loop ............................................................................................................................................ 9 The do…while Statement ..................................................................................................................................... 21 The for Statement ................................................................................................................................................ 23

Nesting for Loops. .......................................................................................................................................... 28 Scope of a Loop control variable .................................................................................................................... 29 PitFall ............................................................................................................................................................. 30

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

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.

Page 2: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

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.

2

Loop body (Usually includes updating the loop variable.

Program execution continues

counter = 1

conditional expression

Initialize the loop variable

Page 3: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

false

true

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.

3

counter <= 1000

Print the number Update counter: counter =

counter + 1

Program execution continues

Page 4: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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: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.

4

Page 5: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

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.

Alternate method using string

5

1. class ReverseNumber2. {3. String s, result;4. int length;5.6. ReverseNumber(int n)7. {8. s = Integer.toString(n);9. result = "";10. length = s.length() - 1;11. }12.13. void reverse()14. {15. while (length >= 0)16. {17. result = result + s.charAt(length);18. length--;19. }20. }21.22. public String toString()23. {24. return "The number is: " + s + "\nwhen reversed it is " + result;25. }26. }

Page 6: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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:

6

Page 7: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

The class SchoolContribution has:

Constantso 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 && totalAmount < 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;

7

Page 8: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

13. day = 0;14. s = "Day \tDaily Contribution\tTotal Contribution\n";15. df = NumberFormat.getCurrencyInstance();16. }

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.

8

Page 9: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

1. import javax.swing.JOptionPane;2. public class TestContribution3. {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.

9

Page 10: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

10

Initialize outer loop

Initialize inner loop

Inner loop body Update inner loop variable

Update outer loop variable

Program exits loops

Page 11: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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. 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;

11

Page 12: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

40. }41. }

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. }

12

Page 13: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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:

13

Page 14: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

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 MailingLabels

14

Tokenize string

hasMoreTokens()

Get nextToken() and process it

Next statement

Page 15: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

3. {4. String s;

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

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");

15

Page 16: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

8. while (!s.equals(""))9. {10.m.makeLabels(s);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){

16

Page 17: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

}

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. {

17

Page 18: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

29. NumberFormat nf = NumberFormat.getInstance();30. DecimalFormat df = (DecimalFormat)nf;31. df.applyPattern("0.00000000");

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++;

}}

}

18

Page 19: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

(b) public class Mystry{

public static void main(String[] arg){

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--;}

}}

19

Page 20: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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:

20

Page 21: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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:

21

conditional_expression

statement

Loop body

Page 22: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

int i = 1;do{

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());

22

Page 23: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

16. }17. }

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

23

condition

data_type id = initial

adjust_idLoop body

Page 24: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

24

statement

i<= 10

int i = 1

…….

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

Page 25: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

1. public class Powers2. {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.

25

Page 26: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

Solution

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.

26

Page 27: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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 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()

27

Page 28: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

14. {15. for (int i = 0; i < halfIndex && palindrome; i++)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.

28

Page 29: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

29

Page 30: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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 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. }

30

Page 31: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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";

31

Page 32: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

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.

32

Page 33: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

33

Page 34: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

34

Page 35: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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.

1. //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.

35

Page 36: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

(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.

2. 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

3. 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

36

Page 37: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

37

Page 38: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

4. 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;

5. 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.

6. 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:

38

Page 39: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

7. 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

39

Page 40: Iterative Statements - School of Computing and …smithjo/classnotes_2xxxx/... · Web viewWrite a Java program that can be used to produce patterns of the following form: The do…while

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

40