Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 8 More Control.

Similar presentations


Presentation on theme: "Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 8 More Control."— Presentation transcript:

1 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 8 More Control Structures

2 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 2 Outline Exception statement Switch statement Do while statement Continue statement

3 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 8.1Exceptions Exception handling is a way for a Java program to detect an exception and execute statements that are designed to deal with the problem. i = j / k; // ArithmeticException occurs if k = 0 acct.deposit(100.00); // NullPointerException occurs if acct is null

4 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Handling Exceptions try block catch ( exception-type identifier ) block try block contains the statements that throw exception. catch block contains statements to be executed if the exception is thrown.

5 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 Handling Exceptions If try block has exception that matches the one named in the catch block, the catch block is executed. If the try block executes normally—without an exception—the catch block is ignored. try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }

6 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Variables and try Blocks Be careful when declaring variables inside a try (or catch ) block. A variable declared inside a block is always local to that block. An example: try { int quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } quotient is local to the try block; it can’t be used outside the try block.

7 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 Variables and try Blocks There’s another trap associated with try blocks. Suppose that the quotient variable is declared immediately before the try block: int quotient; try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } The compiler won’t allow the value of quotient to be accessed later in the program, because no value is assigned to quotient if the exception occurs.

8 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 8 Variables and try Blocks The solution is often to assign a default value to the variable: int quotient = 0; // Default value try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); }

9 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 Accessing Information About an Exception The identifier e in a catch block represents exception object that contains the information about the object. e.getMessage() is used to return the exception message.

10 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 Accessing Information About an Exception An example of printing the message inside an exception object: try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println(e.getMessage()); } If the exception is thrown, the message might be: / by zero

11 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 Terminating the Program After an Exception When an exception is thrown, it may be necessary to terminate the program. Ways to cause program termination: –Execute a return statement in the main method. –Call the System.exit method. try { quotient = dividend / divisor; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1); }

12 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 12 Converting Strings to Integers Convert a string to an int value: Integer.parseInt ( ) –Converting "duh" will fail, causing a NumberFormatException to be thrown. A try-catch block is used to handle the exception: try { n = Integer.parseInt(str); } catch (NumberFormatException e) { // Handle exception }

13 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 Converting Strings to Integers Use try-catch block to prompt the user to enter input for a number form private static int readInt(String prompt) { while (true) { SimpleIO.prompt(prompt); String userInput = SimpleIO.readLine(); try { return Integer.parseInt(userInput); } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); }

14 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 Multiple catch Blocks A try block can be followed by more than one catch block: try { quotient = Integer.parseInt(str1) / Integer.parseInt(str2); } catch (NumberFormatException e) { System.out.println("Error: Not an integer"); } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } When an exception is thrown, the first matching catch block will handle the exception.

15 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 Checked Exceptions Versus Unchecked Exceptions Exceptions fall into two categories. A checked exception: must put try and catch block to handle the exception. Compilation error without try and catch block. An unchecked exception: no need to use try and catch block, but a run time error will happen if an exception happens..

16 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 Checked Exceptions Versus Unchecked Exceptions Some unchecked exceptions: ArithmeticException, NullPointerException, and NumberFormatException. Some checked exceptions: Thread.sleep try { Thread.sleep(100); } catch (InterruptedException e) {} Wrong if no try-catch block!

17 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 8.2 General Form of switch Statement In general, the switch statement has the following appearance: switch ( expression ) { case constant-expression : statements … case constant-expression : statements default : statements } A constant expression is an expression whose value can be determined by the compiler.

18 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 8.2The switch Statement A cascaded if statement can be used to test the value of an expression against a set of possible values: if (day == 1) System.out.println("Sunday"); else if (day == 2) System.out.println("Monday"); else if (day == 3) System.out.println("Tuesday"); else if (day == 4) System.out.println("Wednesday"); else if (day == 5) System.out.println("Thursday"); else if (day == 6) System.out.println("Friday"); else if (day == 7) System.out.println("Saturday");

19 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 The switch Statement Switch statement is used to accomplish the same effect. switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; } Each case ends with a break statement. break statement terminates the switch statement.

20 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 Combining Case Labels Several case labels may correspond to the same action: switch (day) { case 1: System.out.println("Weekend"); break; case 2: System.out.println("Weekday"); break; case 3: System.out.println("Weekday"); break; case 4: System.out.println("Weekday"); break; case 5: System.out.println("Weekday"); break; case 6: System.out.println("Weekday"); break; case 7: System.out.println("Weekend"); break; }

21 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 Combining Case Labels This statement can be shortened by combining cases whose actions are identical: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; }

22 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 Combining Case Labels To save space, several case labels can be put on the same line: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; }

23 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 23 The default Case If the value of the controlling expression in a switch statement doesn’t match any of the case labels, the switch statement is skipped entirely. The word default: can be used as a label for the controlling expression doesn’t match any of the case labels

24 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 24 The default Case An example of a default case: switch (day) { case 1: case 7: System.out.println("Weekend"); break; case 2: case 3: case 4: case 5: case 6: System.out.println("Weekday"); break; default: System.out.println("Not a valid day"); break; }

25 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 25 Advantages of the switch Statement Using switch statements is easier to understand than cascaded if statements Also, the switch statement is often faster than a cascaded if statement. As the number of cases increases, the speed advantage of the switch becomes more significant.

26 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 26 Limitations of the switch Statement The switch statement can’t replace every cascaded if statement. To qualify for conversion to a switch, every test in a cascaded if must compare the same variable (or expression) for equality with a constant: if (x == constant-expression 1 ) statement 1 else if (x == constant-expression 2 ) statement 2 else if (x == constant-expression 3 ) statement 3 …

27 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 27 Limitations of the switch Statement If any value that x is being compared with isn’t constant, a switch statement can’t be used. If the cascaded if statement tests a variety of different conditions, it’s not eligible for switch treatment. A switch statement’s controlling expression must have type char, byte, short, or int.

28 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 28 The Role of the break Statement Each case in a switch statement normally ends with a break statement. If break isn’t present, each case will “fall through” into the next case: switch (sign) { case -1: System.out.println("Negative"); case 0: System.out.println("Zero"); case +1: System.out.println("Positive"); } If sign has the value –1, the statement will print "Negative", "Zero", and "Positive".

29 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 29 Program: Determining the Number of Days in a Month The MonthLength program asks the user for a month (an integer between 1 and 12) and a year, then displays the number of days in that month: Enter a month (1-12): 4 Enter a year: 2003 There are 30 days in this month The program will use a switch statement to determine whether the month has 30 days or 31 days. If the month is February, an if statement will be needed to determine whether February has 28 days or 29 days.

30 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 30 MonthLength.java // Determines the number of days in a month import jpb.*; public class MonthLength { public static void main(String[] args) { // Prompt the user to enter a month SimpleIO.prompt("Enter a month (1-12): "); String userInput = SimpleIO.readLine(); int month = Integer.parseInt(userInput); // Terminate program if month is not between 1 and 12 if (month 12) { System.out.println("Month must be between 1 and 12"); return; } // Prompt the user to enter a year SimpleIO.prompt("Enter a year: "); userInput = SimpleIO.readLine(); int year = Integer.parseInt(userInput);

31 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 31 // Determine the number of days in the month int numberOfDays; switch (month) { case 2: // February numberOfDays = 28; if (year % 4 == 0) { numberOfDays = 29; if (year % 100 == 0 && year % 400 != 0) numberOfDays = 28; } break; case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; default: numberOfDays = 31; break; }

32 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 32 // Display the number of days in the month System.out.println("There are " + numberOfDays + " days in this month"); }

33 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 33 8.3The do Statement Java has three loop statements: while, do, and for. All three use a boolean expression to determine whether or not to continue looping. Which type of loop to use is mostly a matter of convenience. –for is convenient for counting loops. –while is convenient for most other kinds of loops.

34 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 34 General Form of the do Statement A do statement form: do statement while ( expression ) ; The do statement behaves like the while statement, except that the controlling expression is tested after the body of the loop is executed.

35 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 35 General Form of the do Statement Flow of control within a do statement:

36 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 36 An Example of a do Statement The “countdown” example of Section 4.7 rewritten using a do statement: i = 10; do { System.out.println("T minus " + i + " and counting"); --i; } while (i > 0); The only difference between the do statement and the while statement is that the body of a do statement is always executed at least once.

37 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 37 8.4The continue Statement continue statement causes the program to jump to the end of the loop body. The break statement can be used in loops and switch statements; the use of continue is limited to loops. continue is used much less often than break.

38 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 38 Uses of the continue Statement Using continue can simplify the body of a loop by reducing the amount of nesting inside the loop. Consider the following loop: while ( expr1 ) { if ( expr2 ) { statements } A version that uses continue : while ( expr1 ) { if (! expr2 ) continue; statements }

39 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 39 Uses of the continue Statement The continue statement is especially useful for subjecting input to a series of tests. If it fails any test, continue can be used to skip the remainder of the loop. Testing a Social Security number for validity includes checking that it contains three digits, a dash, two digits, a dash, and four digits. The following loop won’t terminate until the user enters an 11-character string with dashes in the right positions.

40 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 40 while (true) { SimpleIO.prompt("Enter a Social Security number: "); ssn = SimpleIO.readLine(); if (ssn.length() < 11) { System.out.println("Error: Number is too short"); continue; } if (ssn.length() > 11) { System.out.println("Error: Number is too long"); continue; } if (ssn.charAt(3) != '-' || ssn.charAt(6) != '-') { System.out.println( "Error: Number must have the form ddd-dd-dddd"); continue; } break; // Input passed all the tests, so exit the loop }

41 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 41 8.5Nested Loops When the body of a loop contains another loop, the loops are said to be nested. Nested loops are quite common, although the loops often aren’t directly related to each other.

42 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 42 An Example of Nested Loops The PhoneDirectory program of Section 5.8 contains a while loop with the following form: while (true) { … if (command.equalsIgnoreCase("a")) { … } else if (command.equalsIgnoreCase("f")) { … for (int i = 0; i < numRecords; i++) { … } } else if (command.equalsIgnoreCase("q")) { … } else { … } … }

43 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 43 Uses of Nested Loops In many cases, one loop is nested directly inside another loop, and the loops are related. Typical situations: –Displaying tables. Printing a table containing rows and columns is normally done by a pair of nested loops. –Working with multidimensional arrays. Processing the elements of a multidimensional array is normally done using nested loops, with one loop for each dimension of the array. –Sorting. Nested loops are also common in algorithms that sort data into order.

44 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 44 Labeled break Statements The break statement transfers control out of the innermost enclosing loop or switch statement. When these statements are nested, the normal break statement can escape only one level of nesting. Consider the case of a switch statement nested inside a while statement: while (…) { switch (…) { … break; … }

45 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 45 Labeled break Statements The break statement transfers control out of the switch statement, but not out of the while loop. Similarly, if a loop is nested inside a loop, executing a break will break out of the inner loop, but not the outer loop. At times, there is a need for a break statement that can break out of multiple levels of nesting.

46 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 46 Labeled break Statements Consider the situation of a program that prompts the user to enter a command. After executing the command, the program asks the user to enter another command: while (true) { Prompt user to enter command ; Execute command ; }

47 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 47 Labeled break Statements A switch statement (or cascaded if statement) will be needed to determine which command the user entered: while (true) { Prompt user to enter command ; switch ( command ) { case command 1 : Perform operation 1 ; break; case command 2 : Perform operation 2 ; break; … case command n : Perform operation n ; break; default: Print error message ; break; }

48 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 48 Labeled break Statements The loop will terminate when the user enters a particular command (command n, say). The program will need a break statement that can break out of the loop, when the user enters the termination command. Java’s labeled break statement can handle situations like this: break identifier ; The identifier is a label chosen by the programmer. The label precedes the loop that should be terminated by the break. A colon must follow the label.

49 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 49 Labeled break Statements A corrected version of the command loop: commandLoop: while (true) { Prompt user to enter command ; switch ( command ) { case command 1 : Perform operation 1 ; break; case command 2 : Perform operation 2 ; break; … case command n : break commandLoop; default: Print error message ; break; } The label doesn’t have to precede a loop. It could label any statement, including an if or switch.

50 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 50 Labeled continue Statements The continue statement normally applies to the nearest enclosing loop. continue is allowed to contain a label, to specify which enclosing loop the statement is trying to affect: continue identifier ; The label must precede one of the enclosing loops. Executing the statement causes the program to jump to the end of that loop, without causing the loop to terminate.

51 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 51 Program: Computing Interest The PrintInterest program prints a table showing the value of $100 invested at different rates of interest over a period of years. The user will enter an interest rate and the number of years the money will be invested. The table will show the value of the money at one- year intervals—at that interest rate and the next four higher rates—assuming that interest is compounded once a year.

52 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 52 Program: Computing Interest An example showing the interaction between PrintInterest and the user: Enter interest rate: 6 Enter number of years: 5 Years 6% 7% 8% 9% 10% 1 106 107 108 109 110 2 112 114 117 119 121 3 119 123 126 130 133 4 126 131 136 141 146 5 134 140 147 154 161

53 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 53 Design of the PrintInterest Program Each row depends on the numbers in the previous row, indicating that an array will be needed to store the values in the current row. Nested for statements will be needed: –The outer loop will count from 1 to the number of years requested by the user. –The inner loop will increment the interest rate from its lowest value to its highest value.

54 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 54 PrintInterest.java // Prints a table showing the value of $100 invested at // different rates of interest over a period of years import jpb.*; public class PrintInterest { public static void main(String[] args) { // Initialize array so that all amounts are equal double[] amounts = new double[5]; for (int i = 0; i < amounts.length; i++) amounts[i] = 100.00; // Prompt user to enter interest rate SimpleIO.prompt("Enter interest rate: "); String userInput = SimpleIO.readLine(); int lowRate = Integer.parseInt(userInput);

55 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 55 // Prompt user to enter number of years SimpleIO.prompt("Enter number of years: "); userInput = SimpleIO.readLine(); int numYears = Integer.parseInt(userInput); // Print a heading for the table. Each column represents // a single interest rate. The lowest rate is the one // entered by the user. Four other rates are shown; each // is 1% higher than the previous one. System.out.print("\nYears"); for (int i = 0; i < amounts.length; i++) printField(lowRate + i + "%", 6); System.out.println();

56 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 56 // Print contents of table; each row represents one // year for (int year = 1; year <= numYears; year++) { printField(year + " ", 5); for (int i = 0; i < amounts.length; i++) { amounts[i] += (lowRate + i) / 100.0 * amounts[i]; printField("" + Math.round(amounts[i]), 6); } System.out.println(); } // Displays str in a field of the specified width, with // spaces added at the beginning if necessary private static void printField(String str, int width) { for (int i = str.length(); i < width; i++) System.out.print(" "); System.out.print(str); }

57 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 57 8.6Case Study: Printing a One-Month Calendar The PrintCalendar program will automatically detect the current month and year, and then display a calendar for that month: May 2000 -------------------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 The month and year will be centered over the calendar.

58 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 58 Design of the PrintCalendar Program An initial design: 1. Determine the current month and year. 2. Determine on which day of the week the current month begins. 3. Display the calendar. Step 1 requires the help of GregorianCalendar, a class that belongs to the java.util package. Step 2 can be done with a standard algorithm such as Zeller’s congruence. However, there’s an easier way to do this step using GregorianCalendar.

59 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 59 The GregorianCalendar Class A GregorianCalendar object created using a constructor with no arguments will contain the current time and date: GregorianCalendar date = new GregorianCalendar(); The get method can be used to access the time and date stored inside a GregorianCalendar object. get returns a single part of the time or date, encoded as an integer. It requires an argument specifying which part should be returned. The argument to get is a constant defined in the Calendar class (also part of java.util ).

60 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 60 The GregorianCalendar Class A partial list of the constants defined in the Calendar class: Name MeaningRange DATE Day of month 1–31 DAY_OF_WEEK Day of the week 1–7 HOUR Hour (12-hour clock) 0–11 HOUR_OF_DAY Hour (24-hour clock) 0–23 MINUTE Minutes 0–59 MONTH Month 0–11 SECOND Seconds 0–59 YEAR Year –

61 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 61 The GregorianCalendar Class A call of get that returns the current year: System.out.println("Current year: " + date.get(Calendar.YEAR)); The set method changes the information stored inside a GregorianCalendar object. Algorithm to determine the day of the week on which the current month began: –Call set to set the date to 1. –Call get to retrieve DAY_OF_WEEK.

62 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 62 Design of Step 3 A design for step 3: 1. Print a heading for the calendar. 2. Print the days in the current month. Two helper methods, printHeading and printDays, will be responsible for these steps.

63 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 63 Design of the printHeading Method A design for printHeading : 1. Convert the month number to a name. 2. Determine how many spaces to display before the month. 3. Print the month, year, and a row of dashes. The month number can be converted to a name by using it as an index into an array containing the names of all 12 months.

64 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 64 Design of the printHeading Method The number of spaces to display before the month depends on: –Width of calendar (20 characters) –Length of month name –Number of characters needed for year and space between month and year (5 total) A formula for the number of spaces: (20 – (number of characters for year and space) – (length of month name))/2 = ( 15 – (length of month name))/2

65 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 65 Design of the printDays Method The printDays method will need to perform the following steps: 1. Leave space for “empty days” at the beginning of the month. 2. Print the days in the current month. Step 1 can be a loop that prints three spaces for each “empty day.” The number of empty days depends on the day of the week for day 1 of the current month.

66 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 66 Design of the printDays Method Step 2 requires a loop with a counter going from 1 to the number of days in the month. The loop body will print the value of the counter. If the counter has only a single digit, the loop will print a space before and after the number; otherwise, it will print a space after the number. The loop body will need to test whether the counter represents a Saturday. If so, the following day will begin on a different output line.

67 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 67 Design of the printDays Method Which dates fall on Saturday depends on what the first day of the month is. –If the month begins on Sunday, then days 7, 14, 21, and 28 are Saturdays. –If the month begins on Monday, then days 6, 13, 20, and 27 are Saturdays. If dayOfWeek is the starting day for the month (where 0  dayOfWeek  6), then day is a Saturday if (dayOfWeek + day) % 7 equals 0.

68 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 68 PrintCalendar.java // Program name: PrintCalendar // Author: K. N. King // Written: 1998-05-07 // Modified: 1999-07-07 // // Displays a calendar for the current month. The calendar // has the following form: // // May 2000 // -------------------- // 1 2 3 4 5 6 // 7 8 9 10 11 12 13 // 14 15 16 17 18 19 20 // 21 22 23 24 25 26 27 // 28 29 30 31 // // The month name and year are centered over the calendar. import java.util.*; import jpb.*;

69 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 69 public class PrintCalendar { public static void main(String[] args) { // Determine the current date GregorianCalendar date = new GregorianCalendar(); // Adjust to first day of month date.set(Calendar.DATE, 1); // Determine the current month and year int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); // Determine the day of the week for the first day of the // current month int dayOfWeek = date.get(Calendar.DAY_OF_WEEK) - 1; // Print a heading for the calendar printHeading(month, year); // Print the body of the calendar printDays(dayOfWeek, daysInMonth(month, year)); }

70 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 70 /////////////////////////////////////////////////////////// // NAME: printHeading // BEHAVIOR: Prints a heading for a one-month calendar. // The heading consists of a month and year, // centered over a row of 20 dashes. // PARAMETERS: month - number representing a month (0-11) // year - the year // RETURNS: Nothing /////////////////////////////////////////////////////////// private static void printHeading(int month, int year) { // Convert the month number to a name final String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; String monthString = MONTH_NAMES[month]; // Determine how many spaces to display before the month int precedingSpaces = (15 - monthString.length()) / 2;

71 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 71 // Print the month, year, and row of dashes System.out.println(); for (int i = 1; i <= precedingSpaces; i++) System.out.print(" "); System.out.println(monthString + " " + year); System.out.println("--------------------"); }

72 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 72 /////////////////////////////////////////////////////////// // NAME: printDays // BEHAVIOR: Prints the days in a one-month calendar // PARAMETERS: dayOfWeek - day of week for first day in // month (0-6) // monthLength - number of days in month // RETURNS: Nothing /////////////////////////////////////////////////////////// private static void printDays(int dayOfWeek, int monthLength) { // Leave space for "empty days" at the beginning of the // month for (int i = 0; i < dayOfWeek; i++) System.out.print(" ");

73 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 73 // Display the calendar. Add a space before each // single-digit day so that columns will line up. Advance // to the next line after each Saturday date is printed. for (int day = 1; day <= monthLength; day++) { if (day <= 9) System.out.print(" " + day + " "); else System.out.print(day + " "); if ((dayOfWeek + day) % 7 == 0) System.out.println(); } // If the month did not end on a Saturday, terminate the // last line of the calendar with a new-line if ((dayOfWeek + monthLength) % 7 != 0) System.out.println(); }

74 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 74 /////////////////////////////////////////////////////////// // NAME: daysInMonth // BEHAVIOR: Computes the number of days in a month. // PARAMETERS: month - number representing a month (0-11) // year - the year // RETURNS: Number of days in the specified month in the // specified year /////////////////////////////////////////////////////////// private static int daysInMonth(int month, int year) { int numberOfDays = 31; // Add 1 to month; the result will be between 1 and 12 switch (month + 1) { case 2: // February numberOfDays = 28; if (year % 4 == 0) { numberOfDays = 29; if (year % 100 == 0 && year % 400 != 0) numberOfDays = 28; } break;

75 Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 75 case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; } return numberOfDays; }


Download ppt "Chapter 8: More Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 8 More Control."

Similar presentations


Ads by Google