|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
assertEquals( 0, Linguistics.countVowels( "" ) ); assertEquals( 0, Linguistics.countVowels( "z" ) ); assertEquals( 0, Linguistics.countVowels( "zxyz" ) ); assertEquals( 1, Linguistics.countVowels( "a" ) ); assertEquals( 1, Linguistics.countVowels( "A" ) ); assertEquals( 0, Linguistics.countVowels( "y" ) ); assertEquals( 0, Linguistics.countVowels( "Y" ) ); assertEquals( 5, Linguistics.countVowels( "aeiou" ) ); assertEquals( 5, Linguistics.countVowels( "AEIOU" ) ); assertEquals( 1, Linguistics.countVowels( "Zyzzyva" ) ); assertEquals( 4, Linguistics.countVowels( "Test Cases, Eh?" ) ); assertEquals( 5, Linguistics.countVowels( "abcdefghijklmnopqrstuvwxyz" ); assertEquals( 0, Linguistics.countVowels( "$%^#!" ) ); |
One of the questions we ask ourselves, when writing a loop, is “how do I do a small task once”? In this case, that's “how do I tell if one particular character is a vowel”?
You should be able to answer this question after perusing standard Java documentation for Strings. Here is what you'd end up with: an expression that tells whether the 17th character of a String s is a vowel:
VOWELS.contains( new Character( s.charAt(16) ).toString() ) |
// Assume 'doggies' is a variable of type a LinkList<Dog>. int totalAgeSoFar = 0; int index = 0; while (index < doggies.size()) { totalAgeSoFar = totalAgeSoFar + (doggies.get(index)).getAge(); index=index+1; } |
int totalAgeSoFar = 0; for ( int index = 0; index < doggies.size(); index=index+1 ) { totalAgeSoFar = totalAgeSoFar + (doggies.get(index)).getAge(); } |
1 If you really want to be fancy, you can ignore spaces and punctuation, so that you'd correctly classify the palindromes “Able was I, ere I saw Elba.” and “A man, a plan, a canal -- Panama!"”. In my own version of this punctuation-ignoring version, I find a while loop very natural to use, (and a for loop awkward), because it's no longer clear in advance exactly how far through the String I'll look at. We'll talk more in lecture about when to use each. ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2007, Ian Barland, Radford University Last modified 2007.Aug.27 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |