![]() |
![]() |
|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
The canonical example of a for loop:
for (int i = 0; i < N; ++i) {
// ... body involving i...
// We'll give an example using System.out.println,
// although printing doesn't actually help accumulate
// any answer worth returning.
}
|
Given a list of Treasures, loot,
Here is another problem worked on in some of the lectures:
/** Return all Strings in a list which start with a given prefix.
* @param msgs The list of Strings to search through.
* @param prefix The string to look for, as a prefix.
* @return all Strings in msgs which start with prefix.
*/
public static LinkedList<String> allMatches( String prefix, LinkedList<String> msgs ) {
LinkedList<String> matchesSoFar = new LinkedList<String>();
for ( String m : msgs ) {
if (startsWith(m , prefix)) {
matchesSoFar.add(m);
}
}
return matchesSoFar;
}
|
/** Does one string have another as a prefix?
* @param text The string to look at the beginning of
* @param prfx The string to try to match at the start of text.
* @return Does text start with the characters inside prfx?
*/
private static boolean startsWith( String text, String prfx ) {
if (text.length() < prfx.length()) {
return false;
}
else {
boolean allMatchSoFar = true;
int i = 0;
while (i < prfx.length()) {
if (prfx.charAt(i) != text.charAt(i)) {
allMatchSoFar = false;
}
i = i+1;
}
return allMatchSoFar;
// Alternately: replace the `if` with:
// allMatchedSoFar &&= (prfx.charAt(i)==text.charAt(i));
// Alternately: replace the entire while-loop with
// return text.substring(0,prfx.length()).equals(prfx)
// (Note that substring and equals each have loops internally.)
}
}
|
1Using return from the middle of a loop is poor style. And using break and continue are unaesthetic, which is why we won't talk about them in class, although you're free to read the book. ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
| ©2007, Ian Barland, Radford University Last modified 2007.Nov.22 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |