Example: Counting Words string sentence inputBox getstring("Enter a sentence: )i int numberof characters sentence length()i int index int wordcount while (index number ofCharacters Problem Inner loops could cause //ignore blank spaces index to become equal to numberofCharacters while(sentence. charAt(index) Which is an error index++ //now locate the end of the word while(sentence. charAt(index)!=)t index++ wordcount+i//another word found, so increment the counter C 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8-11
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 11 Example: Counting Words String sentence = inputBox.getString("Enter a sentence:"); int numberOfCharacters = sentence.length(); int index = 0; int wordCount = 0; while (index < numberOfCharacters ) { //ignore blank spaces while (sentence.charAt(index) == ' ') { index++; } //now locate the end of the word while (sentence.charAt(index) != ' ') { index++; } wordCount++; //another word found, so increment the counter } Problem: Inner loops could cause index to become equal to numberOfCharacters, which is an error
Example: Counting Words-2 String sentence inputBox getstring("Enter a sentence: ) nt numberof Characters= sentence length() nt index Problem nt wordcount word Count will be one more than the actual count if the while (index number ofcharacters sentence ends with one or more spaces //ignore blank spaces while(index numberofcharacters & sentence charAt (index) index++ //now locate the end of the word while (index numberofCharacters & sentence charAt (index)! index++ wordCount ++://another word found, so increment the counter C 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8-12
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--Wu Chapter 8 - 12 Example: Counting Words - 2 String sentence = inputBox.getString("Enter a sentence:"); int numberOfCharacters = sentence.length(); int index = 0; int wordCount = 0; while (index < numberOfCharacters ) { //ignore blank spaces while (index < numberOfCharacters && sentence.charAt(index) == ' ') { index++; } //now locate the end of the word while (index < numberOfCharacters && sentence.charAt(index) != ' ') { index++; } wordCount++; //another word found, so increment the counter } Problem: wordCount will be one more than the actual count if the sentence ends with one or more spaces