import java.util.LinkedList;
/**
* Write a description of class WhilePractice here.
*
* @author Ian Barland
* @version 2006.Oct.16
*/
public class WhilePractice {
/** Open up a URL, and read the input.
* As a side-effect (for demonstration only), print each line to the console.
* @return The number of lines in a given URL.
*/
public static int countLines() throws java.net.MalformedURLException, java.io.IOException {
String sourcePage =
// "http://www.radford.edu"
"http://www.radford.edu/~itec120/2007fall-ibarland/index.html"
// "file:///Users/ian/120/index.html"
;
// Open sourcePage for input: (Create a URL object based on sourcePage, open that URL as a stream-of-characters,
// and create a Scanner who will group that stream's characters into Strings etc.)
java.util.Scanner src = new java.util.Scanner( new java.net.URL( sourcePage ).openStream() );
int linesSoFar = 0; // Keep track of how many lines we've seen.
while ( src.hasNext() ) {
src.nextLine();
linesSoFar = linesSoFar + 1;
}
return linesSoFar;
}
/** Open up a URL, and read the input.
* As a side-effect (for demonstration only), print each line to the console.
* @return The number of lines in a given URL.
*/
public static String getURLText() throws java.net.MalformedURLException, java.io.IOException {
String sourcePage =
// "http://www.radford.edu"
"http://www.radford.edu/~itec120/2007fall-ibarland/index.html"
// "file:///Users/ian/120/index.html"
;
// Open sourcePage for input: (Create a URL object based on sourcePage, open that URL as a stream-of-characters,
// and create a Scanner who will group that stream's characters into Strings etc.)
java.util.Scanner src = new java.util.Scanner( new java.net.URL( sourcePage ).openStream() );
String textSoFar = ""; // Keep track of all words we've seen so far.
while ( src.hasNext() ) {
textSoFar = textSoFar.concat( src.next() );
}
return textSoFar;
}
/** Return a string, counting down from 10.
* @param biggestNum The number where the countdown begins from.
* @return A countdown string.
* Example: countdown() = "3...2...1...Liftoff!"
*
*/
public static String countdown_v0() {
String chantSoFar = ""; /* A local variable, to accumulate the answer. */
int t = 3; /* The next number to count down. */
// Append smaller and smaller numbers to the end of chant:
while (t > 0) {
chantSoFar = chantSoFar + t + "...";
t = t-1;
}
return chantSoFar + "Liftoff!";
}
/** Announce a countdown, starting at startAt.
* @param startAt The number to start the countdown from.
* startAt must be >= 0.
* @param shout A message to shout out, when 0 is reached.
* @return A countdown starting at startAt.
* E.g., "10...9...8... [etc] 2...1...Liftoff!"
*/
public static String countdown_v1( int startAt, String shout ) {
String chantSoFar = ""; /* A local variable, to accumulate the answer. */
int t = startAt; /* The next number to count down. */
if (startAt<0) {
String errMsg = "countdown: startAt must be non-negative; got " + startAt;
System.err.println( errMsg );
// If you really want to be fancy:
throw new java.lang.IllegalArgumentException( errMsg );
}
// Append smaller and smaller numbers onto chant:
while (t > 0) {
chantSoFar = chantSoFar + (t + "...");
t = t-1;
}
return chantSoFar + shout;
}
/** Return a string, counting down from biggestNum.
* @param biggestNum The number where the countdown begins from.
* @param shout A message to shout out, when 0 is reached.
* @return A countdown string.
* Example: countdown_v2( 3, "cheese!" ) = "3...2...1...cheese!"
*/
public static String countdown_v2( int biggestNum, String shout ) {
String chantSoFar = ""; /* A local variable, to accumulate the answer. */
int t = 0; /* The next number to count down. */
// Prepend steadily-larger numbers on to the front of chant:
while (t < biggestNum) {
t = t+1;
chantSoFar = (t + "...") + chantSoFar;
}
return (chantSoFar + shout);
}
/** A warning about your termination condition.
* (a) Find out what is wrong with this program
* (either via debugger, or via println)
* (b) fix it!
*/
public static String countdown_double_bad() {
String chantSoFar = "";
double decrement = 2.0-1.1;
double i = decrement*5;
while (i != 0) {
chantSoFar = chantSoFar + i + "...";
i = i - decrement;
}
return chantSoFar + "Liftoff!";
}
/* A version using a for-loop rather than a while-loop.
*/
public static String countdown_v3() {
String chantSoFar = ""; /* A local variable, to accumulate the answer. */
int COUNTDOWN_START = 10; /* The first number to count down. */
// Append smaller and smaller numbers onto chant:
for ( int t = COUNTDOWN_START; t > 0; --t ) {
chantSoFar = chantSoFar + (t + "...");
}
return (chantSoFar + "Liftoff!");
}
/** Return the nth triangular number.
* @param n The number of rows in a triangle.
* @return The number of pins needed to set up a n rows of pins,
* each row containing one more pin than the previous.
* That is, return 1+2+3+...+(n-1)+n.
* Test cases:
* triangularNumber(4) = 10
* triangularNumber(6) = 21
* triangularNumber(2) = 3
* triangularNumber(1) = 1
* triangularNumber(0) = 0
*/
public static int triangularNumber( int n ) {
int totalSoFar = 0; // The number of pins counted so far.
int rowsSoFar = 0; // The number of rows counted so far.
while (rowsSoFar < n) {
rowsSoFar = rowsSoFar + 1; // Claim another row as counted, and...
totalSoFar = totalSoFar + rowsSoFar; // include that new row in our answer.
}
return totalSoFar;
}
/* Count slightly differently than before:
*/
public static int triangularNumber_v2( int n ) {
int totalSoFar = 0; // The number of pins counted so far.
int nextRow = 1; // The next row we have yet to look at.
while (nextRow <= n) {
totalSoFar += nextRow; // Include that nextRow in our answer.
nextRow += 1; // Update our concept of what nextRow is.
}
return totalSoFar;
}
/* Use a for-loop, rather than a while-loop
*/
public static int triangularNumber_v3( int n ) {
int totalSoFar = 0; // The number of pins counted so far.
for ( int nextRow = 1; nextRow <= n; nextRow = nextRow + 1 ) {
// nextRow is the index of the next row we haven't already seen.
totalSoFar += nextRow;
}
return totalSoFar;
}
/** Return the number of oranges needed to make a n-high square pyramid.
* @param n The height of a square pyramid.
* @return The number of oranges needed to create a square pyramid of height n.
* The i'th layer contains i^2 oranges.
* That is, return 1^2 + 2^2 + 3^2 + ...+ i^2 + ... + (n-1)^2 + n^2.
* Test cases:
* squarePyramidSize(0) = 0
* squarePyramidSize(1) = 1
* squarePyramidSize(2) = 5 = 1 + 4
* squarePyramidSize(3) = 14 = 1 + 4 + 9
* squarePyramidSize(4) = 30 = 1 + 4 + 9 + 16
*/
public static int squarePyramidSize( int n ) {
int totalSoFar = 0; // The number of pins counted so far.
int layersSoFar = 0; // The number of layers counted so far.
// How to look at each layer?
// When looking at a certain layer (say, #7), how many in that one layer?
// How to revise totalSoFar, based on the number in that certain layer?
while (layersSoFar < n) {
layersSoFar = layersSoFar + 1; // Claim another layer as counted, and...
totalSoFar = totalSoFar + layersSoFar*layersSoFar; // include that new layer in our answer.
}
return totalSoFar;
}
/** Return the number of oranges needed to make a n-high triangular pyramid.
* @param n The height of a triangular pyramid.
* @return The number of oranges needed to create a triangular pyramid of height n.
* The i'th layer contains triangularNumer(i) oranges.
* That is, return triangularNumber(1) + triangularNumber(2) + ...
* + triangularNumber(i) + ...
* + triangularNumber(n-1) + triangularNumber(n).
* Test cases:
* triangularPyramidSize(0) = 0
* triangularPyramidSize(1) = 1
* triangularPyramidSize(2) = 4 = 1 + 3
* triangularPyramidSize(3) = 10 = 1 + 3 + 6
* triangularPyramidSize(3) = 20 = 1 + 3 + 6 + 10
*/
public static int triangularPyramidSize( int n ) {
int totalSoFar = 0; // The number of pins counted so far.
int currentLayer = 0; // The number of layers counted so far.
while (currentLayer < n) {
currentLayer = currentLayer + 1; // Claim another layer as counted, and...
totalSoFar = totalSoFar + currentLayer * currentLayer; // include that new layer in our answer.
}
return totalSoFar;
}
/**
* 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 static String directoryListing( String directoryName ) {
// Convert the directoryName into a File object, so we can get its size etc.:
java.io.File theDirectory = new java.io.File( directoryName );
// Note that we import'd java.io.File.
if (theDirectory.isDirectory()) {
long fileLengthsSoFar = 0; // Accumulate the sum of all immediate file sizes.
String listingSoFar = "";
for ( java.io.File f : theDirectory.listFiles() ) { // For each `f' in the directory-listing...
fileLengthsSoFar += f.length(); // Add f's length to our sum.
listingSoFar += f.toString() + "\t\t\t" + f.length() + "\n";
}
return listingSoFar + "\nTotal length: " + fileLengthsSoFar + "\n";
}
else {
// Hmm, this file wasn't a directory; print a message to System.err.
String errMsg = "immediateDirectorySize: " + directoryName + " is not the name of a directory.";
System.err.println( errMsg );
return errMsg; // Is this an appropriate sentinel value? I want to return 'false', but can't!
}
}
/** 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.)
}
}
/** 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 allMatches( String prefix, LinkedList msgs ) {
LinkedList matchesSoFar = new LinkedList();
for ( String m : msgs ) {
if (startsWith(m , prefix)) {
matchesSoFar.add(m);
}
}
return matchesSoFar;
}
}