import java.io.File; class WhilePractice { /** * @param theDogs a *non-empty* list, to find the average age of. */ double averageAgeOf( java.util.LinkedList theDogs ) { double sumOfAges = 0.0; for (Dog d : theDogs) { sumOfAges = sumOfAges + d.getAge(); } return (sumOfAges / theDogs.size()); } /** Return an oldest Dog in a list of Dogs. * @param theDogs The list of dogs to find the oldest of. * Must be a non-empty list. * @return an oldest Dog in a list of Dogs. */ Dog oldestDog( java.util.LinkedList theDogs ) { Dog oldestSoFar = theDogs.get(0); for ( Dog d : theDogs ) { if (d.getAge() > oldestSoFar.getAge()) { oldestSoFar = d; } } return oldestSoFar; } /** Return a list of *all* oldest Dogs, in a list of Dogs. * @param theDogs The list of dogs to find the oldest of. * @return a list of all the Dogs in the input which are tied for oldest-age. * If the input list was empty, we return a (new) empty list. */ java.util.LinkedList oldestDogs( java.util.LinkedList theDogs ) { java.util.LinkedList retirementHome = new java.util.LinkedList(); if (theDogs.isEmpty()) { return retirementHome; // If no dogs in input, then no dogs are oldest. } Dog anOldestDog = oldestDog( theDogs ); for ( Dog d : theDogs ) { if (d.getAge() == anOldestDog.getAge()) { retirementHome.add( d ); } } return retirementHome; } /** Return The sum of the length of each file immediately inside directoryName. * Doesn't recur into any sub-directories (but does include any size a directory * itself takes up, aside from its sub-contents). * @param directoryName The pathname of a directory. * @return The sum of the length of each file immediately inside directoryName. */ public long directorySizeToplevel( String directoryName ) { // Convert the directoryName into a File object, so we can get its size etc.: File theDirectory = new File( directoryName ); // Since we imported java.io.File above, we don't need to use its full name. if (theDirectory.isDirectory()) { long sizeSoFar = 0; // Accumulate the sum of all immediate file sizes. for ( File f : theDirectory.listFiles() ) { // For each `f' in the directory, sizeSoFar = sizeSoFar + f.length(); // Add f's length to our sum. } return sizeSoFar; } else { // Hmm, this file wasn't a directory; print a message to System.err. String errMsg = "directorySizeTopLevel: " + directoryName + " is not the name of a directory."; System.err.println( errMsg ); return -1; // Is this an appropriate sentinel value? I want to return 'false', but can't! } } }