Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Review 2.

Slides:



Advertisements
Similar presentations
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Advertisements

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Chapter 4  Fundamental Data Types 1 Chapter 4 Fundamental Data Types.
Chapter 6 Iteration Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
Datalogi A 5: 6/10. while Loops Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement; Most.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 6  Iteration 1 Chapter 6 Iteration. Chapter 6  Iteration 2 Chapter Goals  To be able to program loops with while and for (sometimes do ) statements.
Chapter 8 Testing and Debugging Goals To learn how to carry out unit tests To understand the principles of test case selection and evaluation To learn.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Java Basics (continued)
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Chapter 4: Fundamental Data Types. To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware.
Chapter 4 Numeric types & arithmetic Strings: reading & writing.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 3 – Fundamental Data Types.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To recognize.
Java Programming: From the Ground Up
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Chapter 10 Testing and Debugging. Chapter Goals To learn how to carry out unit tests To understand the principles of test case selection and evaluation.
Fall 2006Adapted from Java Concepts Companion Slides1 Testing and Debugging Advanced Programming ICOM 4015 Lecture 9 Reading: Java Concepts Chapter 10.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
Fall 2006Slides adapted from Java Concepts companion slides1 Fundamental Data Types Advanced Programming ICOM 4015 Lecture 4 Reading: Java Concepts Chapter.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 6 Chapter.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Copyright © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 6 - Loops.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 6 - Loops.
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
Chapter 10 Testing and Debugging. Chapter Goals ► To learn how to carry out unit tests ► To understand the principles of test case selection and evaluation.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 6 – Iteration.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
If Statement if (amount
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Chapter 6 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
Decisions Bush decision making.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A string is a sequence of characters Strings are objects of the String.
Chapter 7 Iteration. Chapter Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To.
A final variable is a constant
Chapter Six: Iteration
Chapter Goals To understand integer and floating-point numbers
Chapter Goals To implement while, for, and do loops
Lecture Notes – Basics (Ch1-6)
Chapter 6 – Loops.
Selected Topics From Chapter 6 Iteration
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 10 Testing and Debugging
LOOPS.
Chapter Six - Iteration
Chapter 4 – Fundamental Data Types
Chapter 7 Iteration.
4.3 Arithmetic Operators and Mathematical Functions
Presentation transcript:

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Review 2

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A final variable is a constant Once its value has been set, it cannot be changed Named constants make programs easier to read and maintain Convention: use all-uppercase names for constants final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01; payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE; Constants: final

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. If constant values are needed in several methods, declare them together with the instance fields of a class and tag them as static and final Give static final constants public access to enable other classes to use them public class Math {... public static final double E = ; public static final double PI = ; } double circumference = Math.PI * diameter; Constants: static final

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. In a method: final typeName variableName = expression; In a class: accessSpecifier static final typeName variableName = expression; Example: final double NICKEL_VALUE = 0.05; public static final double LITERS_PER_GALLON = 3.785; Purpose: To define a constant in a method or a class. Syntax 4.2 Constant Definition

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Assignment is not the same as mathematical equality: items = items + 1; items++ is the same as items = items + 1 items-- subtracts 1 from items Assignment, Increment, and Decrement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Assignment, Increment, and Decrement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. / is the division operator If both arguments are integers, the result is an integer. The remainder is discarded 7.0 / 4 yields / 4 yields 1 Get the remainder with % (pronounced "modulo") 7 % 4 is 3 Arithmetic Operations

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. final int PENNIES_PER_NICKEL = 5; final int PENNIES_PER_DIME = 10; final int PENNIES_PER_QUARTER = 25; final int PENNIES_PER_DOLLAR = 100; // Compute total value in pennies int total = dollars * PENNIES_PER_DOLLAR + quarters * PENNIES_PER_QUARTER + nickels * PENNIES_PER_NICKEL + dimes * PENNIES_PER_DIME + pennies; // Use integer division to convert to dollars, cents int dollars = total / PENNIES_PER_DOLLAR; int cents = total % PENNIES_PER_DOLLAR; Arithmetic Operations

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Math class: contains methods like sqrt and pow To compute x n, you write Math.pow(x, n) However, to compute x 2 it is significantly more efficient simply to compute x * x To take the square root of a number, use the Math.sqrt ; for example, Math.sqrt(x ) In Java, can be represented as (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a) The Math class

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What is the value of 1729 / 100 ? Of 1729 % 100 ? Answer: 17 and 29 Self Check 4.8

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ClassName.methodName(parameters) Example: Math.sqrt(4) Purpose: To invoke a static method (a method that does not operate on an object) and supply its parameters. Syntax 4.3 Static Method Call

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why can't you call x.pow(y ) to compute x y ? Answer: x is a number, not an object, and you cannot invoke methods on numbers. Self Check 4.11

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Is the call System.out.println(4 ) a static method call? Answer: No – the println method is called on the object System.out. Self Check 4.12

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A string is a sequence of characters Strings are objects of the String class String constants: "Hello, World!" String variables: String message = "Hello, World!"; String length: int n = message.length(); Empty string: "" Strings

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Use the + operator: String name = "Dave"; String message = "Hello, " + name; // message is "Hello, Dave" If one of the arguments of the + operator is a string, the other is converted to a string String a = "Agent"; int n = 7; String bond = a + n; // bond is "Agent7" Concatenation

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Useful to reduce the number of System.out.print instructions System.out.print("The total is "); System.out.println(total); versus System.out.println("The total is " + total); Concatenation in Print Statements

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. String greeting = "Hello, World!"; String sub = greeting.substring(0, 5); // sub is "Hello" Supply start and “past the end” position First position is at 0 Continued Substrings

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Substring length is “past the end” - start Substrings (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Assuming the String variable s holds the value "Agent", what is the effect of the assignment s = s + s.length () ? Answer: s is set to the string Agent5 Self Check 4.13

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. System.in has minimal set of features–it can only read one byte at a time In Java 5.0, Scanner class was added to read keyboard input in a convenient manner Scanner in = new Scanner(System.in); System.out.print("Enter quantity:"); int quantity = in.nextInt(); nextDouble reads a double nextLine reads a line (until user hits Enter) nextWord reads a word (until any white space) Reading Input

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.util.Scanner; 02: 03: /** 04: This program simulates a transaction in which a user pays for an item 05: and receives change. 06: */ 07: public class CashRegisterSimulator 08: { 09: public static void main(String[] args) 10: { 11: Scanner in = new Scanner(System.in); 12: 13: CashRegister register = new CashRegister(); 14: 15: System.out.print("Enter price: "); 16: double price = in.nextDouble(); 17: register.recordPurchase(price); 18: 19: System.out.print("Enter dollars: "); 20: int dollars = in.nextInt(); Continued ch04/cashregister/CashRegisterSimulator.java

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Output: Enter price: 7.55 Enter dollars: 10 Enter quarters: 2 Enter dimes: 1 Enter nickels: 0 Enter pennies: 0 Your change: is 3.05 ch04/cashregister/CashRegisterSimulator.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. The if statement lets a program carry out different actions depending on a condition If (amount <= balance) balance = balance – amount; The if Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. If (amount <= balance) balance = balance – amount; else balance = balance – OVERDRAFT_PENALTY The if / else Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Simple statement balance = balance - amount; Compound statement if (balance >= amount) balance = balance - amount; Also while, for, etc. (loop statements – Chapter 6) Block statement { double newBalance = balance - amount; balance = newBalance; } Statement Types

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. if(condition) statement if (condition) statement 1 else Example: if (amount <= balance) balance = balance - amount; if (amount <= balance) balance = balance - amount; else Purpose: To execute a statement when a condition is true or false. Syntax 5.1 The if Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. { statement 1 statement 2... } Example: { double newBalance = balance - amount; balance = newBalance; } Purpose: To group several statements together to form a single statement. Syntax 5.2 Block Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What is logically wrong with the statement if (amount <= balance) newBalance = balance - amount; balance = newBalance; and how do you fix it? Answer: Only the first assignment statement is part of the if statement. Use braces to group both assignment statements into a block statement. Self Check 5.2

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: if (input.equals("Y")) == tests identity, equals tests equal contents Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) s.compareTo(t) < 0 means: s comes before t in the dictionary Continued Comparing Strings

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. "car" comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car" Comparing Strings (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Nested Branches (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. && and || or ! not if (0 < amount && amount < 1000)... if (input.equals("S") || input.equals("M"))... Using Boolean Expressions: The Boolean Operators

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. && and || Operators

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. AB A && B true false Any false AB A || B true Any true falsetrue false A ! A truefalse true Truth Tables

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Executes a block of code repeatedly A condition controls how often the loop is executed while (condition) statement Most commonly, the statement is a block statement (set of statements delimited by { } ) while Loops

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. YearBalance 0$10,000 1$10,500 2$11,025 3$11, $12, $12, Invest $10,000, 5% interest, compounded annually Calculating the Growth of an Investment

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. while Loop Flowchart

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. while (condition) statement Example: while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; } Purpose: To repeatedly execute a statement as long as a condition is true. Syntax 6.1 The while Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. int years = 0; while (years < 20) { double interest = balance * rate / 100; balance = balance + interest; } int years = 20; while (years > 0) { years++; // Oops, should have been years– double interest = balance * rate / 100; balance = balance + interest; } Loops run forever – must kill program Common Error: Infinite Loops

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Executes loop body at least once: do statement while (condition); Example: Validate input double value; do { System.out.print("Please enter a positive number: "); value = in.nextDouble(); } while (value <= 0); do Loops Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Alternative: boolean done = false; while (!done) { System.out.print("Please enter a positive number: "); value = in.nextDouble(); if (value > 0) done = true; } do Loops (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. do Loop Flowchart

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Spaghetti Code

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } Equivalent to initialization; while (condition) { statement; update; } for Loops Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Other examples: for (years = n; years > 0; years--)... for (x = -10; x <= 10; x = x + 0.5)... for Loops (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. for Loop Flowchart

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. for (initialization; condition; update) statement Example: for (int i = 1; i <= n; i++) { double interest = balance * rate / 100; balance = balance + interest; } Purpose: To execute an initialization, then keep executing a statement and updating an expression while a condition is true. Syntax 6.2 The for Statement

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sentinel value: Can be used for indicating the end of a data set 0 or -1 make poor sentinels; better use Q System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")) We are done else { double x = Double.parseDouble(input);... } Processing Sentinel Values

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sometimes termination condition of a loop can only be evaluated in the middle of the loop Then, introduce a boolean variable to control the loop: boolean done = false; while (!done) { Print prompt String input = read input; if (end of input indicated) done = true; else { Process input } } Loop and a half

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. In a simulation, you repeatedly generate random numbers and use them to simulate an activity Random number generator Random generator = new Random(); int n = generator.nextInt(a); // 0 < = n < a double x = generator.nextDouble(); // 0 <= x < 1 Throw die (random number between 1 and 6) int d = 1 + generator.nextInt(6); Random Numbers and Simulations

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.util.Random; 02: 03: /** 04: This class models a die that, when cast, lands on a random 05: face. 06: */ 07: public class Die 08: { 09: /** 10: Constructs a die with a given number of sides. s the number of sides, e.g. 6 for a normal die 12: */ 13: public Die(int s) 14: { 15: sides = s; 16: generator = new Random(); 17: } 18: 19: /** 20: Simulates a throw of the die the face of the die 22: */ ch06/random1/Die.java Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 23: public int cast() 24: { 25: return 1 + generator.nextInt(sides); 26: } 27: 28: private Random generator; 29: private int sides; 30: } ch06/random1/Die.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: /** 02: This program simulates casting a die ten times. 03: */ 04: public class DieSimulator 05: { 06: public static void main(String[] args) 07: { 08: Die d = new Die(6); 09: final int TRIES = 10; 10: for (int i = 1; i <= TRIES; i++) 11: { 12: int n = d.cast(); 13: System.out.print(n + " "); 14: } 15: System.out.println(); 16: } 17: } ch06/random1/DieSimulator.java

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Output: Second Run: ch06/random1/DieSimulator.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. How do you use a random number generator to simulate the toss of a coin? Answer: int n = generator.nextInt(2); // 0 = heads, 1 = tails Self Check 6.9

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Debugger = program to run your program and analyze its run-time behavior A debugger lets you stop and restart your program, see contents of variables, and step through it The larger your programs, the harder to debug them simply by inserting print commands Debuggers can be part of your IDE (e.g. Eclipse, BlueJ) or separate programs (e.g. JSwat) Three key concepts: Breakpoints Single-stepping Inspecting variables Using a Debugger

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Execution is suspended whenever a breakpoint is reached In a debugger, a program runs at full speed until it reaches a breakpoint When execution stops you can: Inspect variables Step through the program a line at a time Or, continue running the program at full speed until it reaches the next breakpoint When program terminates, debugger stops as well Breakpoints stay active until you remove them Two variations of single-step command: Step Over: skips method calls Step Into: steps inside method calls Debugging

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Current line: String input = in.next(); Word w = new Word(input); int syllables = w.countSyllables(); System.out.println("Syllables in " + input + ": " + syllables); When you step over method calls, you get to the next line: String input = in.next(); Word w = new Word(input); int syllables = w.countSyllables(); System.out.println("Syllables in " + input + ": " + syllables); Single-step Example Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. However, if you step into method calls, you enter the first line of the countSyllables method public int countSyllables() { int count = 0; int end = text.length() - 1;... } Single-step Example (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. In the debugger, you are reaching a call to System.out.println. Should you step into the method or step over it? Answer: You should step over it because you are not interested in debugging the internals of the println method. Self Check 6.11

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. In the debugger, you are reaching the beginning of a long method with a couple of loops inside. You want to find out the return value that is computed at the end of the method. Should you set a breakpoint, or should you step through the method? Answer: You should set a breakpoint. Stepping through loops can be tedious. Self Check 6.12

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: /** 02: This class describes words in a document. 03: */ 04: public class Word 05: { 06: /** 07: Constructs a word by removing leading and trailing non- 08: letter characters, such as punctuation marks. s the input string 10: */ 11: public Word(String s) 12: { 13: int i = 0; 14: while (i < s.length() && !Character.isLetter(s.charAt(i))) 15: i++; 16: int j = s.length() - 1; 17: while (j > i && !Character.isLetter(s.charAt(j))) 18: j--; 19: text = s.substring(i, j); 20: } 21: ch06/debugger/Word.java Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 22: /** 23: Returns the text of the word, after removal of the 24: leading and trailing non-letter characters. the text of the word 26: */ 27: public String getText() 28: { 29: return text; 30: } 31: 32: /** 33: Counts the syllables in the word. the syllable count 35: */ 36: public int countSyllables() 37: { 38: int count = 0; 39: int end = text.length() - 1; 40: if (end < 0) return 0; // The empty string has no syllables 41: ch06/debugger/Word.java (cont.) Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 42: // An e at the end of the word doesn't count as a vowel 43: char ch = Character.toLowerCase(text.charAt(end)); 44: if (ch == 'e') end--; 46: boolean insideVowelGroup = false; 47: for (int i = 0; i <= end; i++) 48: { 49: ch = Character.toLowerCase(text.charAt(i)); 50: String vowels = "aeiouy"; 51: if (vowels.indexOf(ch) >= 0) 52: { 53: // ch is a vowel 54: if (!insideVowelGroup) 55: { 56: // Start of new vowel group 57: count++; 58: insideVowelGroup = true; 59: } 60: } 61: } 62: ch06/debugger/Word.java (cont.) Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 63: // Every word has at least one syllable 64: if (count == 0) 65: count = 1; 66: 67: return count; 68: } 69: 70: private String text; 71: } ch06/debugger/Word.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 01: import java.util.Scanner; 02: 03: /** 04: This program counts the syllables of all words in a sentence. 05: */ 06: public class SyllableCounter 07: { 08: public static void main(String[] args) 09: { 10: Scanner in = new Scanner(System.in); 11: 12: System.out.println("Enter a sentence ending in a period."); 13: 14: String input; 15: do 16: { 17: input = in.next(); 18: Word w = new Word(input); 19: int syllables = w.countSyllables(); 20: System.out.println("Syllables in " + input + ": " 21: + syllables); 22: } ch06/debugger/SyllableCounter.java Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. 23: while (!input.endsWith(".")); 24: } 25: } ch06/debugger/SyllableCounter.java (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Continued Debug the Program Buggy output (for input " hello yellow peach. "): Syllables in hello: 1 Syllables in yellow: 1 Syllables in peach.: 1 Set breakpoint in first line of countSyllables of Word class Start program, supply input. Program stops at breakpoint Method checks if final letter is ' e '

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Check if this works: step to line where check is made and inspect variable ch Should contain final letter but contains ' l ' Debug the Program (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. end is set to 3, not 4 text contains " hell ", not " hello " No wonder countSyllables returns 1 More Problems Found Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Culprit is elsewhere Can't go back in time Restart and set breakpoint in Word constructor More Problems Found (cont.)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Supply " hello " input again Break past the end of second loop in constructor Inspect i and j They are 0 and 4 – makes sense since the input consists of letters Why is text set to " hell "? Off-by-one error: Second parameter of substring is the first position not to include text = substring(i, j); should be text = substring(i, j + 1); Debugging the Word Constructor

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Debugging the Word Constructor

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Fix the error Recompile Test again: Syllables in hello: 1 Syllables in yellow: 1 Syllables in peach.: 1 Oh no, it's still not right Start debugger Erase all old breakpoints and set a breakpoint in countSyllables method Supply input " hello. " Another Error

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Break in the beginning of countSyllables. Then, single-step through loop boolean insideVowelGroup = false; for (int i = 0; i <= end; i++) { ch = Character.toLowerCase(text.charAt(i)); if ("aeiouy".indexOf(ch) >= 0) { // ch is a vowel if (!insideVowelGroup) { // Start of new vowel group count++; insideVowelGroup = true; } } } Debugging countSyllables (again) Continued

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. First iteration ( 'h' ): skips test for vowel Second iteration (' e '): passes test, increments count Third iteration (' l '): skips test Fifth iteration (' o '): passes test, but second if is skipped, and count is not incremented Debugging countSyllables (again)

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. insideVowelGroup was never reset to false Fix if ("aeiouy".indexOf(ch) >= 0) {... } else insideVowelGroup = false; Retest: All test cases pass Syllables in hello: 2 Syllables in yellow: 2 Syllables in peach.: 1 Is the program now bug-free? The debugger can't answer that. Fixing the Bug

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What caused the first error that was found in this debugging session? Answer: The programmer misunderstood the second parameter of the substring method–it is the index of the first character not to be included in the substring. Self Check 6.13

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. What caused the second error? How was it detected? Answer: The second error was caused by failing to reset insideVowelGroup to false at the end of a vowel group. It was detected by tracing through the loop and noticing that the loop didn't enter the conditional statement that increments the vowel count. Self Check 6.14

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. The First Bug