+ All Categories
Home > Documents > Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control...

Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control...

Date post: 14-Jan-2016
Category:
Upload: dustin-singleton
View: 227 times
Download: 3 times
Share this document with a friend
104
1 Chapter 8: More Control Structures Java Java Programming Programming FROM THE BEGINNING FROM THE BEGINNING Chapter 8 More Control Structures
Transcript
Page 1: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

1

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Chapter 8

More Control Structures

Page 2: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

2

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

8.1 Exceptions

• When a Java program performs an illegal operation, an exception happens.

• If a program has no special provisions for dealing with exceptions, it will behave badly if one occurs.

• In many cases, the program will terminate immediately.

• Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem.

• This process is called exception handling.

Page 3: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

3

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Common Exceptions

• There are many kinds of exceptions, each with a different name.

• Common exceptions:– ArithmeticException– NullPointerException

• Trying to divide by zero causes an ArithmeticException:i = j / k; // ArithmeticException occurs if k = 0

Page 4: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

4

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Common Exceptions

• Using zero as the right operand in a remainder operation also causes an ArithmeticException:i = j % k; // ArithmeticException occurs if k = 0

• Calling a method using an object variable whose value is null causes a NullPointerException:acct.deposit(100.00); // NullPointerException occurs if acct is null

Page 5: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

5

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Handling Exceptions

• When an exception occurs (is thrown), the program has the option of catching it.

• In order to catch an exception, the code in which the exception might occur must be enclosed in a try block.

• After the try block comes a catch block that catches the exception (if it occurs) and performs the desired action.

Page 6: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

6

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Handling Exceptions

• The try and catch blocks together form a single statement, which can be used anywhere in a program that a statement is allowed:try blockcatch (exception-type identifier) block

• exception-type specifies what kind of exception the catch block should handle.

• identifier is an arbitrary name.

Page 7: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

7

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Handling Exceptions

• If an exception is thrown within the try block, and the exception matches the one named in the catch block, the code in the catch block is executed.

• If the try block executes normally—without an exception—the catch block is ignored.

• An example of try and catch blocks:try { quotient = dividend / divisor;} catch (ArithmeticException e) { System.out.println("Error: Division by zero");}

Page 8: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

8

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 9: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

9

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 10: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

10

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Variables and try Blocks

• The solution is often to assign a default value to the variable:int quotient = 0; // Default valuetry { quotient = dividend / divisor;} catch (ArithmeticException e) { System.out.println("Error: Division by zero");}

Page 11: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

11

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Accessing InformationAbout an Exception

• When an exception occurs, Java creates an “exception object” that contains information about the error.

• The identifier in a catch block (typically e) represents this object.

• Every exception object contains a string. The getMessage method returns this string:e.getMessage()

Page 12: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

12

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Accessing InformationAbout 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

• Printing the value returned by getMessage can be useful if it’s not clear what the error is or what caused it.

Page 13: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

13

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Terminating the ProgramAfter 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.

Page 14: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

14

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Terminating the ProgramAfter an Exception

• Adding a call of System.exit to a catch block will cause the program to terminate:try { quotient = dividend / divisor;} catch (ArithmeticException e) { System.out.println("Error: Division by zero"); System.exit(-1);}

• A program that terminates abnormally should supply a nonzero argument (typically –1) to System.exit.

Page 15: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

15

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Converting Strings to Integers

• Attempting to convert a string to an int value using Integer.parseInt may fail:– Converting "123" will succeed.

– Converting "duh" will fail, causing a NumberFormatException to be thrown.

• A robust program should provide a catch block to handle the exception:try { n = Integer.parseInt(str);} catch (NumberFormatException e) { // Handle exception}

Page 16: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

16

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Converting Strings to Integers

• If the string contains user input, it’s often a good idea to have the user re-enter the input.

• Putting the try and catch blocks in a loop allows the user multiple attempts to enter a valid number:while (true) { SimpleIO.prompt("Enter an integer: "); String userInput = SimpleIO.readLine(); try { n = Integer.parseInt(userInput); break; // Input was valid; exit the loop } catch (NumberFormatException e) { System.out.println("Not an integer; try again."); }}

Page 17: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

17

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Converting Strings to Integers

• The loop could be put inside a class method that prompts the user to enter a number and then returns the user’s input in integer 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."); } }}

Page 18: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

18

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 19: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

19

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Checked Exceptions VersusUnchecked Exceptions

• Exceptions fall into two categories.• A checked exception must be dealt with by the

program. The compiler will produce an error if there is no try block and catch block to handle the exception.

• An unchecked exception can be ignored by the programmer; there’s no need to use try and catch to handle the exception.

Page 20: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

20

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Checked Exceptions VersusUnchecked Exceptions

• Some unchecked exceptions represent disasters so severe that there’s no hope of continuing program execution.

• Others represent errors that could potentially occur at hundreds of places in a program, including ArithmeticException, NullPointerException, and NumberFormatException.

• Checked exceptions represent conditions that the programmer should be able to anticipate and deal with.

Page 21: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

21

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Checked Exceptions VersusUnchecked Exceptions

• The Thread.sleep method may throw InterruptedException, which is a checked exception.

• Thread.sleep allows a program to “go to sleep” for a specified time interval:Thread.sleep(100);

• The sleep time is measured in milliseconds.

Page 22: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

22

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Checked Exceptions VersusUnchecked Exceptions

• Calling Thread.sleep outside a try block will cause the compiler to display a message saying that “InterruptedException must be caught.”

• To avoid getting an error from the compiler, a call of Thread.sleep should be put in a try block:try { Thread.sleep(100);} catch (InterruptedException e) {}

Page 23: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

23

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Exceptions Properly

• try and catch blocks aren’t meant to be used as ordinary control structures.

• In most cases, it’s better to test for an error before it occurs rather than wait until it happens and then catch the resulting exception.

• Consider the following loop:while (n != 0) { r = m % n; m = n; n = r;}

Page 24: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

24

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Exceptions Properly

• The loop could be written in the following way:try { while (true) { r = m % n; m = n; n = r; }} catch (ArithmeticException e) {}

• The loop still works, but it’s harder to figure out when the loop will terminate. Also, the code is longer and more deeply nested.

Page 25: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

25

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Exceptions Properly

• Another disadvantage of using exceptions when they’re not strictly necessary: a catch block may catch exceptions that were never anticipated.

• For example, a catch block that catches ArithmeticException may end up handling errors other than just division by zero.

Page 26: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

26

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Exceptions Properly

• Exceptions should be used when it’s not possible to test for errors before performing an operation.

• There’s no easy way to test whether the characters in a string form a valid integer.

• The best way to find out is to call a conversion method, such as Integer.parseInt.

• If Integer.parseInt detects a problem during the conversion, it throws an exception to notify the program of the error.

Page 27: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

27

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 28: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

28

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The switch Statement

• There’s a better way to accomplish the same effect.

• Java’s switch statement is designed specifically for comparing a variable (or, more generally, an expression) against a series of possible values.

Page 29: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

29

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The switch Statement

• An equivalent switch statement: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;}

Page 30: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

30

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The switch Statement

• When a switch statement is executed, the expression in parentheses (the controlling expression) is evaluated.

• The value of the controlling expression is then compared with the values listed after the word case (the case labels).

• If a match is found, the statements after the matching case label are executed.

Page 31: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

31

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The switch Statement

• Each case ends with a break statement.• Executing a break statement causes the switch

statement to terminate.• The program continues executing with the

statement that follows the switch statement.

Page 32: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

32

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 33: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

33

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 34: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

34

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 35: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

35

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

• To indicate a default action to occur whenever the controlling expression doesn’t match any of the case labels, the word default: can be used as a label.

Page 36: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

36

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 37: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

37

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The General Form of theswitch 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.

Page 38: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

38

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The General Form of theswitch Statement

• Case labels don’t have to go in any particular order, although it’s good style to put the labels in a logical order.

• The default label doesn’t have to go last, although that’s where most programmers put it.

• It’s illegal for the same value to appear in two case labels.

• Any number of statements (including none at all) can go after each case label.

• Normally, the last statement in each case is break.

Page 39: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

39

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Layout of the switch Statement

• There are at least two common ways to lay out a switch statement.

• One layout technique puts the first statement in each case on the same line as the case label:switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break;}

Page 40: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

40

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Layout of the switch Statement

• When there’s only one statement per case (not counting break), programmers often save space by putting the break statement on the same line:switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break;}

• The other common layout involves putting the statements in each case under the case label, indenting them to make the case label stand out.

Page 41: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

41

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Layout of the switch Statement

• Example:switch (year) { case 1992: olympicSite = "Barcelona"; break; case 1996: olympicSite = "Atlanta"; break; case 2000: olympicSite = "Sydney"; break; case 2004: olympicSite = "Athens"; break;}

Page 42: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

42

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Layout of the switch Statement

• Although this layout allows longer statements, it also increases the number of lines required for the switch statement.

• This layout is best used when there are many statements in each case or the statements are lengthy.

Page 43: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

43

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Advantages of the switch Statement

• The switch statement has two primary advantages over the cascaded if statement.

• Using switch statements instead of cascaded if statements can make a program easier to understand.

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

Page 44: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

44

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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-expression1) statement1

else if (x == constant-expression2) statement2

else if (x == constant-expression3) statement3

Page 45: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

45

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 46: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

46

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 47: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

47

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The Role of the break Statement

• The case labels in a switch statement are just markers that indicate possible places to enter the list of statements inside the braces.

• Omitting the break statement is sometimes a useful programming technique, but most of the time it’s simply a mistake.

• Putting a break statement at the end of the last case makes it easier (and less risky) to add additional cases.

Page 48: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

48

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Program: Determining theNumber 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): 4Enter a year: 2003There 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.

Page 49: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

49

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 50: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

50

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 51: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

51

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Display the number of days in the month System.out.println("There are " + numberOfDays + " days in this month"); }}

Page 52: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

52

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 53: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

53

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

General Form of the do Statement

• A do statement looks like a while statement in which the controlling expression and body have switched positions:do statementwhile ( expression ) ;

• The do statement behaves like the while statement, except that the controlling expression is tested after the body of the loop is executed.

Page 54: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

54

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

General Form of the do Statement

• Flow of control within a do statement:

Page 55: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

55

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 56: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

56

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Finding the Number of Digits in an Integer

• Although the do statement isn’t used as often as the while statement, it’s handy in some cases.

• One way to determine the number of digits in an integer is to use a loop to divide the integer by 10 repeatedly until it becomes 0.

• The number of divisions performed is the number of digits.

Page 57: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

57

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Finding the Number of Digits in an Integer

• The do statement is a better choice than the while statement, because every integer—even 0—has at least one digit.

• A do loop that computes the number of digits in the integer n:numDigits = 0;do { numDigits++; n /= 10;} while (n > 0);

Page 58: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

58

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Finding the Number of Digits in an Integer

• A trace of the loop, assuming that n has the value 5392 initially:

Initial After After AfterAfter

value iteration 1 iteration 2 iteration 3iteration 4numDigits 0 1 2 3 4n 5392 539 53 5 0

• When the loop terminates, numDigits has the value 4, which is the number of digits in 5392.

Page 59: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

59

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Finding the Number of Digits in an Integer

• A corresponding while loop:numDigits = 0;while (n > 0) { numDigits++; n /= 10;}

• If n is 0 initially, this loop won’t execute at all, and numDigits will end up with the value 0.

Page 60: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

60

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using Braces in do Statements

• Many programmers use braces in all do statements, whether or not they’re needed

• A do statement without braces around its body can be mistaken for a while statement:do System.out.println("T minus " + i-- + " and counting");while (i > 0);

Page 61: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

61

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

8.4 The continue Statement

• Java’s continue statement is similar to the break statement.

• Unlike break, executing a continue statement doesn’t cause a loop to terminate. Instead, it 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.

Page 62: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

62

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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}

Page 63: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

63

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 64: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

64

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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}

Page 65: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

65

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 66: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

66

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 { … } …}

Page 67: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

67

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 68: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

68

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 69: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

69

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 70: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

70

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 71: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

71

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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 command1: Perform operation1; break; case command2: Perform operation2; break; … case commandn: Perform operationn; break; default: Print error message; break; }}

Page 72: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

72

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Labeled break Statements

• The loop will terminate when the user enters a particular command (commandn, 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.

Page 73: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

73

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Labeled break Statements

• A corrected version of the command loop:commandLoop: while (true) { Prompt user to enter command; switch (command) { case command1: Perform operation1; break; case command2: Perform operation2; break; … case commandn: 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.

Page 74: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

74

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 75: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

75

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 76: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

76

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Program: Computing Interest

• An example showing the interaction between PrintInterest and the user:Enter interest rate: 6Enter 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

Page 77: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

77

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 78: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

78

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 79: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

79

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 80: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

80

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 81: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

81

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Fields

• The printField method is a helper whose job is to print a string in a “field” of a certain width.

• If the string’s length is less than the specified width, printField displays extra spaces before the string, so that the total number of characters printed (spaces plus the characters in the string) equals the width.

Page 82: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

82

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Fields

• The table is arranged into fields. Each line begins with a single 5-character field, followed by five 6-character fields:

• The columns in the table will still line up properly when the years become two-digit numbers and the dollar amounts increase to four or five digits.

Page 83: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

83

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

8.6 Case Study: Printing aOne-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 1314 15 16 17 18 19 2021 22 23 24 25 26 2728 29 30 31

• The month and year will be centered over the calendar.

Page 84: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

84

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 85: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

85

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 86: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

86

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The GregorianCalendar Class

• A partial list of the constants defined in the Calendar class: Name Meaning RangeDATE Day of month 1–31DAY_OF_WEEK Day of the week 1–7 HOUR Hour (12-hour clock) 0–11HOUR_OF_DAY Hour (24-hour clock) 0–23MINUTE Minutes 0–59MONTH Month 0–11SECOND Seconds 0–59YEAR Year –

Page 87: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

87

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 88: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

88

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 89: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

89

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 90: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

90

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 91: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

91

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 92: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

92

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 93: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

93

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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.

Page 94: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

94

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 95: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

95

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 96: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

96

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 97: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

97

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// 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("--------------------"); }

Page 98: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

98

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 99: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

99

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 100: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

100

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

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

Page 101: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

101

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; }

return numberOfDays; }}

Page 102: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

102

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

8.7 Debugging

• When a program fails to catch an exception, the Java interpreter will print information about the nature and location of the exception.

• Knowing how to interpret this information makes debugging much easier and faster.

• Consider what happens if line 121 of the PrintCalendar program isif (year % 0 == 4) {

instead ofif (year % 4 == 0) {

Page 103: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

103

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Output of the Interpreter

• Output of the Java interpreter when the modified PrintCalendar program is executed:Exception in thread "main" java.lang.ArithmeticException: / by zero at PrintCalendar.daysInMonth(PrintCalendar.java:121) at PrintCalendar.main(PrintCalendar.java:42)

• What this message means:– An ArithmeticException occurred.

– The exception occurred on line 121 of PrintCalendar.java. The method that was executing at the time was daysInMonth.

– daysInMonth had been called on line 42 of main.

Page 104: Chapter 8: More Control Structures Java Programming FROM THE BEGINNING 1 Chapter 8 More Control Structures.

104

Chapter 8: More Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Stack Traces

• When an exception is not caught, the Java interpreter displays a stack trace: a list showing what method was executing at the time of the exception, which method called it, and so on.

• Sometimes an exception will be thrown inside one of Java’s own methods, causing the interpreter to mention methods and files that belong to the Java API.


Recommended