































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Smith; Class: Programming I; Subject: Computer Programming; University: Florida International University; Term: Unknown 1989;
Typology: Study notes
1 / 39
This page cannot be seen from the preview
Don't miss anything!
































The while Statement .............................................................................................................................................. 2 Nested while Loop............................................................................................................................................ 8 The do…while Statement ..................................................................................................................................... 20 The for Statement ................................................................................................................................................ 22 Nesting for Loops........................................................................................................................................... 28 Scope of a Loop control variable.................................................................................................................... 29 PitFall............................................................................................................................................................. 29 Pitfall I – Updating the loop variable incorrectly................................................................................. 29 Pitfall II – Modifying the loop variable in loop body........................................................................... 29
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. Java provides three forms of iterative statements. These are the while statement, the do…while statement, and the for 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. 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.. Loop body (Usually includes updating the loop variable. Program execution continues counter = 1 conditional expression Initialize the loop variable
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:
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.
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 TestContribution 3. { 4. public static void main(String[] arg) 5. { 6. SchoolContribution s = new SchoolContribution(); **_7. while (s. hasNotMadeTarget() && s.hasMoreTime())
The while statement like the if statement, can be nested. Recall that the format of the while statement is: while (condition)
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. Write a class called Sales that prints the sales and the total sales for each of the stores, row by row.
5._ public class TestSales 6. { 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. }
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. 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:
Get nextToken() and process it Next statement
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..
1. import java.util.StringTokenizer; 2. public class MailingLabels 3. { 4. String s; 5. MailingLabels() { s = ""; } **_6. void makeLabels(String str)
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 amount save 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 PI 4. { 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"); 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.
while (j >= 1) { System.out.println("\t" + j); j--; } System.out.println("---------"); i--; } } }
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 conditional_express ion Loop body