*****************************
Speedboat.java Illustrates inheritance from Ship class. See SpeedboatTest.java for a test.
*****************************
/** A fast Ship. Red and going 20 knots by default.
*
***********************
public class Speedboat extends Ship {
private String color = "red";
/** Builds a red Speedboat going N at 20 knots. */
public Speedboat(String name) {
super(name);
setSpeed(20);
}
/** Builds a speedboat with specified parameters. */
public Speedboat(double x, double y, double speed,
double direction, String name,
String color) {
super(x, y, speed, direction, name);
setColor(color);
}
/** Report location. Override version from Ship. */
public void printLocation() {
System.out.print(getColor().toUpperCase() + " ");
super.printLocation();
}
/** Gets the Speedboat's color. */
public String getColor() {
return(color);
}
/** Sets the Speedboat's color. */
public void setColor(String colorName) {
color = colorName;
}
}
**********************
SpeedboatTest.java
**********************
/** Try a couple of Speedboats and a regular Ship.
*
*****************************
public class SpeedboatTest {
public static void main(String[] args) {
Speedboat s1 = new Speedboat("Speedboat1");
Speedboat s2 = new Speedboat(0.0, 0.0, 2.0, 135.0,
"Speedboat2", "blue");
Ship s3 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship1");
s1.move();
s2.move();
s3.move();
s1.printLocation();
s2.printLocation();
s3.printLocation();
}
}
*****************************
Aug 29
Speedboat.java Illustrates inheritance from Ship class
Aug 29
Demonstrates overloading methods in class Ship4
*********************
class Ship4 {
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name;
// This constructor takes the parameters explicitly.
public Ship4(double x, double y, double speed,
double direction, String name) {
this.x = x;
this.y = y;
this.speed = speed;
this.direction = direction;
this.name = name;
}
// This constructor requires a name but lets you accept
// the default values for x, y, speed, and direction.
public Ship4(String name) {
this.name = name;
}
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
}
// Move one step.
public void move() {
move(1);
}
// Move N steps.
public void move(int steps) {
double angle = degreesToRadians(direction);
x = x + (double)steps * speed * Math.cos(angle);
y = y + (double)steps * speed * Math.sin(angle);
}
public void printLocation() {
System.out.println(name + " is at (" + x + "," + y + ").");
}
}
public class Test4 {
public static void main(String[] args) {
Ship4 s1 = new Ship4("Ship1");
Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0, "Ship2");
s1.move();
s2.move(3);
s1.printLocation();
s2.printLocation();
}
}
************************
Aug 29
HelloWWW.java Basic Hello World (Wide Web) Applet
*********************
import java.applet.Applet;
import java.awt.*;
*********************
public class HelloWWW extends Applet {
private int fontSize = 40;
public void init() {
setBackground(Color.black);
setForeground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, fontSize));
}
public void paint(Graphics g) {
g.drawString("Hello, World Wide Web.", 5, fontSize+5);
}
}
<<<<<<<<<<<<<<<<<<<<<
Aug 29
Basic Hello World application
*******************
HelloWorld.java Basic Hello World application.
*******************
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world.");
}
}
/*
Aug 29
StringTest.java Demonstrates various methods of the String class.
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class StringTest {
public static void main (String[] args) {
String str = "";
if (args.length > 0) {
str = args[0];
}
if (str.length()>8) {
System.out.println("String is \"" + str + "\"\n");
System.out.println(" charAt(3) ------------------ " +
str.charAt(3));
System.out.println(" compareTo(Moscow) ---------- " +
str.compareTo("Moscow"));
System.out.println(" concat(SuFFiX) ------------- " +
str.concat("SuFFiX"));
System.out.println(" endsWith(hic) -------------- " +
str.endsWith("hic"));
System.out.println(" == Geographic -------------- " +
(str == "Geographic"));
System.out.println(" equals(geographic) --------- " +
str.equals("geographic"));
System.out.println(" equalsIgnoreCase(geographic) " +
str.equalsIgnoreCase("geographic"));
System.out.println(" indexOf('o') --------------- " +
str.indexOf('o'));
System.out.println(" indexOf('i',5) ------------- " +
str.indexOf('i',5));
System.out.println(" indexOf('o',5) ------------- " +
str.indexOf('o',5));
System.out.println(" indexOf(rap) --------------- " +
str.indexOf("rap"));
System.out.println(" indexOf(rap, 5) ------------ " +
str.indexOf("rap", 5));
System.out.println(" lastIndexOf('o') ----------- " +
str.lastIndexOf('o'));
System.out.println(" lastIndexOf('i',5) --------- " +
str.lastIndexOf('i',5));
System.out.println(" lastIndexOf('o',5) --------- " +
str.lastIndexOf('o',5));
System.out.println(" lastIndexOf(rap) ----------- " +
str.lastIndexOf("rap"));
System.out.println(" lastIndexOf(rap, 5) -------- " +
str.lastIndexOf("rap", 5));
System.out.println(" length() ------------------- " +
str.length());
System.out.println(" replace('c','k') ----------- " +
str.replace('c','k'));
System.out.println(" startsWith(eog,1) ---------- " +
str.startsWith("eog",1));
System.out.println(" startsWith(eog) ------------ " +
str.startsWith("eog"));
System.out.println(" substring(3) --------------- " +
str.substring(3));
System.out.println(" substring(3,8) ------------- " +
str.substring(3,8));
System.out.println(" toLowerCase() -------------- " +
str.toLowerCase());
System.out.println(" toUpperCase() -------------- " +
str.toUpperCase());
System.out.println(" trim() --------------------- " +
str.trim());
System.out.println("\nString is still \"" + str + "\"\n");
}
}
}
Aug 29
NegativeLengthException.java Illustrates defining and throwing your own exceptions.
import java.io.*;
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class NegativeLengthException extends Exception {
/** Test NegativeLengthException */
public static void main(String[] args) {
try {
int lineLength = readLength();
for(int i=0; i
Aug 29
TreeTest.java Builds a binary tree and prints the contents of the nodes. Uses the following classes:
Treetest.java
/** A NodeOperator that prints each node.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
class PrintOperator implements NodeOperator {
public void operateOn(Node node) {
System.out.println(node.getNodeValue());
}
}
/** A sample tree representing a parse tree of
* the sentence "Java hackers hack Java", using
* some simple context-free grammar.
*/
public class TreeTest {
public static void main(String[] args) {
Node adjective =
new Node(" Adjective", new Leaf(" Java"));
Node noun1 =
new Node(" Noun", new Leaf(" hackers"));
Node verb =
new Node(" TransitiveVerb", new Leaf(" hack"));
Node noun2 =
new Node(" Noun", new Leaf(" Java"));
Node np = new Node(" NounPhrase", adjective, noun1);
Node vp = new Node(" VerbPhrase", verb, noun2);
Node sentence = new Node("Sentence", np, vp);
PrintOperator printOp = new PrintOperator();
System.out.println("Depth first traversal:");
sentence.depthFirstSearch(printOp);
System.out.println("\nBreadth first traversal:");
sentence.breadthFirstSearch(printOp);
}
}
Leaf.java
A leaf node with no children.
/** Leaf node: a node with no subtrees.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class Leaf extends Node {
public Leaf(Object value) {
super(value, null, null);
}
}
Node.java A data structure representing a node in a binary tree.
import java.util.Vector;
/** A data structure representing a node in a binary tree.
* It contains a node value and a reference (pointer) to
* the left and right subtrees.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class Node {
private Object nodeValue;
private Node leftChild, rightChild;
/** Build Node with specified value and subtrees. */
public Node(Object nodeValue, Node leftChild,
Node rightChild) {
this.nodeValue = nodeValue;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
/** Build Node with specified value and L subtree. R child
* will be null. If you want both children to be null, use
* the Leaf constructor.
*/
public Node(Object nodeValue, Node leftChild) {
this(nodeValue, leftChild, null);
}
/** Return the value of this node. */
public Object getNodeValue() {
return(nodeValue);
}
/** Specify the value of this node. */
public void setNodeValue(Object nodeValue) {
this.nodeValue = nodeValue;
}
/** Return the L subtree. */
public Node getLeftChild() {
return(leftChild);
}
/** Specify the L subtree. */
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
/** Return the R subtree. */
public Node getRightChild() {
return(rightChild);
}
/** Specify the R subtree. */
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
/** Traverse the tree in depth-first order, applying
* the specified operation to each node along the way.
*/
public void depthFirstSearch(NodeOperator op) {
op.operateOn(this);
if (leftChild != null) {
leftChild.depthFirstSearch(op);
}
if (rightChild != null) {
rightChild.depthFirstSearch(op);
}
}
/** Traverse the tree in breadth-first order, applying the
* specified operation to each node along the way.
*/
public void breadthFirstSearch(NodeOperator op) {
Vector nodeQueue = new Vector();
nodeQueue.addElement(this);
Node node;
while(!nodeQueue.isEmpty()) {
node = (Node)nodeQueue.elementAt(0);
nodeQueue.removeElementAt(0);
op.operateOn(node);
if (node.getLeftChild() != null) {
nodeQueue.addElement(node.getLeftChild());
}
if (node.getRightChild() != null) {
nodeQueue.addElement(node.getRightChild());
}
}
}
}
NodeOperator.java An interface used in the Node class to ensure that an object has an operateOn method.
/** An interface used in the Node class to ensure that
* an object has an operateOn method.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public interface NodeOperator {
void operateOn(Node node);
}
Aug 29
Illustrates the use of arrays
/** Report on a round of golf at St. Andy?s.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class Golf {
public static void main(String[] args) {
int[] pars = { 4,5,3,4,5,4,4,3,4 };
int[] scores = { 5,6,3,4,5,3,2,4,3 };
report(pars, scores);
}
/** Reports on a short round of golf. */
public static void report(int[] pars, int[] scores) {
for(int i=0; i
Aug 29
Factorial.java Computes an exact factorial, n!, using a BigInteger
import java.math.BigInteger;
/** Computes an exact factorial, using a BigInteger.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class Factorial {
public static void main(String[] args) {
for(int i=1; i<=256; i*=2) {
System.out.println(i + "!=" + factorial(i));
}
}
public static BigInteger factorial(int n) {
if (n <= 1) {
return(new BigInteger("1"));
} else {
BigInteger bigN = new BigInteger(String.valueOf(n));
return(bigN.multiply(factorial(n - 1)));
}
}
}
Aug 29
Exec.java Provides static methods for running external processes from applications.
import java.io.*;
/** A class that eases the pain of running external processes
* from applications. Lets you run a program three ways:
*
*
exec: Execute the command, returning
* immediately even if the command is still running.
* This would be appropriate for printing a file.
*
execWait: Execute the command, but don?t
* return until the command finishes. This would be
* appropriate for sequential commands where the first
* depends on the second having finished (e.g.,
* javac followed by java).
*
execPrint: Execute the command and print the
* output. This would be appropriate for the Unix
* command ls.
*
* Note that the PATH is not taken into account, so you must
* specify the full pathname to the command, and shell
* built-in commands will not work. For instance, on Unix the
* above three examples might look like:
*
*
Exec.exec("/usr/ucb/lpr Some-File");
*
Exec.execWait("/usr/local/bin/javac Foo.java");
* Exec.execWait("/usr/local/bin/java Foo");
*
Exec.execPrint("/usr/bin/ls -al");
*
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class Exec {
private static boolean verbose = true;
/** Determines if the Exec class should print which commands
* are being executed, and prints error messages if a problem
* is found. Default is true.
*
* @param verboseFlag true: print messages, false: don?t.
*/
public static void setVerbose(boolean verboseFlag) {
verbose = verboseFlag;
}
/** Will Exec print status messages? */
public static boolean getVerbose() {
return(verbose);
}
/** Starts a process to execute the command. Returns
* immediately, even if the new process is still running.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins (e.g., "cd") or shell
* meta-chars (e.g. ">") are allowed.
* @return false if a problem is known to occur, but since
* this returns immediately, problems aren?t usually found
* in time. Returns true otherwise.
*/
public static boolean exec(String command) {
return(exec(command, false, false));
}
/** Starts a process to execute the command. Waits for the
* process to finish before returning.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins or shell metachars are
* allowed.
* @return false if a problem is known to occur, either due
* to an exception or from the subprocess returning a
* nonzero value. Returns true otherwise.
*/
public static boolean execWait(String command) {
return(exec(command, false, true));
}
/** Starts a process to execute the command. Prints any output
* the command produces.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins or shell meta-chars are
* allowed.
* @return false if a problem is known to occur, either due
* to an exception or from the subprocess returning a
* nonzero value. Returns true otherwise.
*/
public static boolean execPrint(String command) {
return(exec(command, true, false));
}
/** This creates a Process object via Runtime.getRuntime.exec()
* Depending on the flags, it may call waitFor on the process
* to avoid continuing until the process terminates, and open
* an input stream from the process to read the results.
*/
private static boolean exec(String command,
boolean printResults,
boolean wait) {
if (verbose) {
printSeparator();
System.out.println("Executing '" + command + "'.");
}
try {
// Start running command, returning immediately.
Process p = Runtime.getRuntime().exec(command);
// Print the output. Since we read until there is no more
// input, this causes us to wait until the process is
// completed.
if(printResults) {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = null;
try {
while ((s = buffer.readLine()) != null) {
System.out.println("Output: " + s);
}
buffer.close();
if (p.exitValue() != 0) {
if (verbose) {
printError(command + " -- p.exitValue() != 0");
}
return(false);
}
} catch (Exception e) {
// Ignore read errors; they mean the process is done.
}
// If not printing the results, then we should call waitFor
// to stop until the process is completed.
} else if (wait) {
try {
System.out.println(" ");
int returnVal = p.waitFor();
if (returnVal != 0) {
if (verbose) {
printError(command);
}
return(false);
}
} catch (Exception e) {
if (verbose) {
printError(command, e);
}
return(false);
}
}
} catch (Exception e) {
if (verbose) {
printError(command, e);
}
return(false);
}
return(true);
}
private static void printError(String command,
Exception e) {
System.out.println("Error doing exec(" + command + "): " +
e.getMessage());
System.out.println("Did you specify the full " +
"pathname?");
}
private static void printError(String command) {
System.out.println("Error executing ?" + command + "?.");
}
private static void printSeparator() {
System.out.println
("==============================================");
}
}
