|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
We talk about overriding methods and giving some brief examples.
Then we review:
Write a method which takes an array-of-strings
and a target word to look for,
and
returns how many time that word occurs.
(This is extremely similar to other loops we've written in class;
we do worry about how to compare Strings in Java, though.)
Should this method be static?
Why or why not?
public static boolean countOccurrences( String[] text, String target ) { int occurrencesSoFar = 0; int i = 0; while ( i < text.length ) { if (text[i].equals(target)) { ++occurrencesSoFar; } } return occurrencesSoFar; } |
How about a related question:
Given an array-of-strings and a target word to look for,
return whether or not that word occurs.
Hint: this is very short, if you call our previous method! (How do we call a static method, again?)
public static boolean contains( String[] text, String target ) { return (countOccurrences(text,target) > 0); } |
That previous method works, and passes all its test cases. However, if we start thinking about efficiency (something to worry about only after we get a working prototype), then we wonder: If given an array of the tens of thousands of words in War and Peace, and asked to search for "inheritance" (which occurs in chapter 1), how much work do we do?
Let's make a new version of boolean contains(String[],String): one that stops as soon as it finds its answer. Our accumulator is different — now we just accumulate whether or not our target has been seenItSoFar, and our condition on the loop has changed: continue while there are more words to look at, and we haven't already seenItSoFar.
public static boolean contains( String[] text, String target ) { boolean seenItSoFar = false; int i = 0; while ( i < text.length && !seenItSoFar ) { if (text[i].equals(target)) { seenItSoFar = true; } } // If we made it all the way through text, then seenItSoFar will still be false. return seenItSoFar; } |
Advanced: In fact, if we are facile with boolean values, we can actually make the update of “seenItSoFar” look more in the vein of “i = i + 1”:
public static boolean contains( String[] text, String target ) { boolean seenItSoFar = false; int i = 0; while ( i < text.length && !seenItSoFar ) { seenItSoFar = seenItSoFar || (text[i].equals(target)); } // If we made it all the way through text, then seenItSoFar will still be false. return seenItSoFar; } |
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.May.03 (Sun) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |