Contents
- ./ArraysExample.java
- ./Calculator.java
- ./Chicken.java
- ./MathTest.java
- ./OverloadPlay.java
- ./TemperatureTable.java
- ./TemperatureTableStatic.java
./ArraysExample.java 1/7
[top][prev][next]
// import the Arrays class so that we can use its functionality
import java.util.Arrays;
/**
* This class demonstrates using arrays and the Arrays class
*
* @author Sara Sprenkle
*
*/
public class ArraysExample {
/**
* Called when user runs
* java ArraysExample
*/
public static void main(String[] args) {
double[] array = new double[10];
// fill the array with PI... mmm... pie... using the Arrays class
Arrays.fill(array, Math.PI);
for( int i=0; i < array.length; i++ ) {
System.out.println("array[" + i + "] = " + array[i]);
}
}
}
./Calculator.java 2/7
[top][prev][next]
/**
* A simple calculator.
* Goal: Practice writing static methods.
*/
public class Calculator {
public static void main(String[] args) {
System.out.println("Average: " + average(1, 2));
}
}
./Chicken.java 3/7
[top][prev][next]
import java.util.Scanner;
/**
* A Java class that represents a chicken. The state of the chicken is
* its name, height and weight. There is also a static variable
* representing the name of the farm that the Chickens live on.
*
* Added static methods and fields
*
* Run program with the argument "test" to test the class.
*
* @author Sara Sprenkle
*/
public class Chicken {
// ------------ INSTANCE VARIABLES -------------------
/** the name of the chicken */
private String name;
/** the height of the chicken in centimeters */
private int height;
/** the weight of the chicken in pounds */
private double weight;
// ------------ CLASS VARIABLES ------------------
/** the name of the farm the chickens are on */
private static String farm = "McDonald";
// -- these are never going to change for the class,
// so they are final
/** the amount of weight the chicken gains during feeding */
private static final double WEIGHT_GAIN = .3;
/** the amount of height the chicken gains during feeding */
private static final int HEIGHT_GAIN = 1;
/** the amount of weight difference we are okay with */
public static final double ERROR_TOLERANCE = .0001;
/**
* Create a new Chicken object with the charactistics as specified by the
* parameters.
* @param name the name of the chicken
* @param height the height of the chicken in centimeters
* @param weight the weight of the chicken in pounds
*/
public Chicken(String name, int height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
/**
* Default name: "Bubba"; height and weight specified by parameters
* @param height the height of the chicken in centimeters
* @param weight the weight of the chicken in pounds
*/
public Chicken(int height, double weight) {
// if the user doesn't specify a name, let's make it Bubba
this("Bubba", height, weight);
}
//
// ----------- GETTER METHODS ------------
// (also Accessor methods)
/**
* Returns the chicken's height, in centimeters
*
* @return the height of the chicken, in centimeters
*/
public int getHeight() {
return this.height;
}
/**
* Returns the chicken's weight, in pounds
*
* @return the weight of the chicken, in pounds
*/
public double getWeight() {
return weight;
}
/**
* Returns the chicken's name
*
* @return the name of the chicken
*/
public String getName() {
return name;
}
//
// ------------- MUTATORS -----------
//
/**
* Feeds the chicken, increasing the chicken's weight and height
*/
public void feed() {
weight += WEIGHT_GAIN;
height += HEIGHT_GAIN;
}
//
// ------------- SETTERS ----------
//
/**
* Sets the name of the chicken
*
* @param n the name of the chicken
*/
public void setName(String n) {
name = n;
}
/**
* Sets the height of the chicken, in cm
*
* @param h the height of the chicken, in cm
*/
public void setHeight(int h) {
height = h;
}
/**
* Sets the weight of the chicken, in pounds
*
* @param w the weight of the chicken, in pounds
*/
public void setWeight(double w) {
weight = w;
}
/**
* Returns a string representation of the chicken.
* Format:
* <br/>Chicken name: <name>
* <br/>weight: <weight> pounds
* <br/>height: <height> cm
* <p>Weight is displayed to one decimal place
* @return a string representation of this Chicken
*/
@Override
public String toString() {
// Use a StringBuilder: more efficient than concatenating strings.
StringBuilder rep = new StringBuilder("Chicken name: ");
rep.append(name);
rep.append("\n\tweight: ");
rep.append(String.format("%.1f", weight)); // guesses as to what this does?
rep.append(" pounds\n");
rep.append("\theight: ");
rep.append(height);
rep.append(" cm");
return rep.toString();
}
/**
* Determines if the Object o is equivalent to this Chicken,
* based on their name, height, and weight.
* @param o the object to compare
* @return true if this object is the same as the o argument (by name, height, and wight). Otherwise, returns false.
*/
@Override
public boolean equals(Object o) {
// Follows the _Effective Java_ process
if( o == this ) {
return true;
}
if( ! ( o instanceof Chicken ) ) {
return false;
}
Chicken other = (Chicken) o;
if( ! other.getName().equals(this.getName() ) ) {
return false;
}
if( other.getHeight() != this.getHeight() ) {
return false;
}
if( Double.compare( other.getWeight(), this.getWeight()) == 0 ) {
return true;
}
// if the weight is close enough, let's consider them
// equivalent
double difference = this.getWeight() - other.getWeight();
if( difference > -ERROR_TOLERANCE && difference < ERROR_TOLERANCE ) {
return true;
}
return false;
}
/**
* This method tests the class.
*/
private static void test() {
int fredHeight = 38;
Chicken chicken = new Chicken("Fred", fredHeight, 2.0);
System.out.println(chicken);
if( chicken.getHeight() != fredHeight ) {
System.err.println("Problem likely in constructor setting height");
}
if( !chicken.getName().equals("Fred") ) {
System.err.println("Problem likely in constructor setting name");
}
chicken.feed();
int newFredHeight = chicken.getHeight();
System.out.println();
System.out.println(chicken.getName() + " is now " + newFredHeight +
" cm tall.");
chicken.feed();
System.out.println("He's a growing boy at " + chicken.getHeight() + " cm tall and " + chicken.getWeight() + " pounds");
System.out.println("\nLook at this beautiful formatting: ");
System.out.println(chicken);
String expectedRep = "Chicken name: Fred\n\tweight: 2.6 pounds\n\theight: 40 cm";
String actualRep = chicken.toString();
// Test the toString method
if( ! actualRep.equals(expectedRep) ) {
System.err.println("Problem in toString");
System.err.println("\tActual: " + actualRep);
System.err.println("\tExpected: " + expectedRep);
}
Chicken trivialMatch = chicken;
// Test equals method
if( ! chicken.equals(trivialMatch) ) {
System.err.println("Problem in equals");
System.err.println("\tActual: " + chicken.equals(trivialMatch) );
System.err.println("\tExpected: " + true);
}
Chicken grownFred = new Chicken("Fred", 40, 2.6);
// Works because we have some error tolerance in weight comparison
if( ! chicken.equals(grownFred) ) {
System.err.println("Problem in equals");
System.err.println("\tActual: " + chicken.equals(grownFred) );
System.err.println("\tExpected: " + true);
}
// ---- creating tests for chickens -----
String[] names = {"Rocky", "Baby Chicken"};
double[] weights = {4.0, .8};
int[] heights = {50, 4};
String[] newNames = {"Rocky II", "Chicken"};
for( int i=0; i < names.length; i++ ) {
Chicken thisChicken = new Chicken( names[i], heights[i], weights[i] );
if( !thisChicken.getName().equals(names[i]) ) {
System.err.println("Problem likely in constructor setting name");
System.err.println("\tActual: " + thisChicken.getName());
System.err.println("\tExpected: " + names[i]);
}
if( thisChicken.getWeight() != weights[i] ) {
System.err.println("\tError in getWeight for Chicken " + i );
System.err.println("\tActual: " + thisChicken.getWeight());
System.err.println("\tExpected: " + weights[i] );
}
// feed the chicken and check the state
thisChicken.feed();
if( thisChicken.getWeight() != weights[i] + WEIGHT_GAIN ) {
System.err.println("Error in feed weight for Chicken " + i);
System.err.println("\tActual: " + thisChicken.getWeight());
System.err.println("\tExpected: " + (weights[i] + WEIGHT_GAIN) );
}
if( thisChicken.getHeight() != heights[i] + HEIGHT_GAIN ) {
System.err.println("Error in feed height for Chicken " + i);
System.err.println("\tActual: " + thisChicken.getHeight());
System.err.println("\tExpected: " + (heights[i] + HEIGHT_GAIN) );
}
// feed the chicken again and check the state
thisChicken.feed();
// NOTE: this test may fail, but tried to address by giving some
// error tolerance on the weight
double expectedWeight2 = weights[i] + 2 * WEIGHT_GAIN;
int comparison = Double.compare(thisChicken.getWeight(), expectedWeight2 );
if( comparison != 0 ) {
if( thisChicken.getWeight() - expectedWeight2 > ERROR_TOLERANCE ) {
System.err.println("Error in second feed weight for Chicken " + i);
System.err.println("\tActual: " + thisChicken.getWeight());
System.err.println("\tExpected: " + (expectedWeight2 ));
}
}
if( thisChicken.getHeight() != heights[i] + 2 * HEIGHT_GAIN ) {
System.err.println("Error in second feed height for Chicken " + i);
System.err.println("\tActual: " + thisChicken.getHeight());
System.err.println("\tExpected: " + (heights[i] + 2 * HEIGHT_GAIN ));
}
thisChicken.setName(newNames[i]);
if( !thisChicken.getName().equals(newNames[i]) ) {
System.err.println("Problem likely in setName");
System.err.println("\tActual: " + thisChicken.getName());
System.err.println("\tExpected: " + newNames[i]);
}
}
// --- Test when equals should return false ---
Chicken[] notQuiteFreds = new Chicken[3];
notQuiteFreds[0] = new Chicken("fred", 40, 2.6);
notQuiteFreds[1] = new Chicken("Fred", 39, 2.6);
notQuiteFreds[2] = new Chicken("Fred", 40, 2.7);
for( int i=0; i < notQuiteFreds.length; i++ ) {
// expect that equals is false for all cases
if( chicken.equals(notQuiteFreds[i] ) ) {
System.err.println("Problem likely in equals");
System.err.println("\tFred: " + chicken);
System.err.println("\tNot Fred: " + notQuiteFreds[i]);
}
}
}
/**
* Return the name of the Chickens' farm
* @return the name of the Chickens' farm
*/
public static String getFarm() {
return farm;
}
/**
* Feeds the given chicken the requested number of times.
*
* @param chicken the chicken to feed
* @param numTimes the number of times to feed the chicken
*/
public static void feedChicken(Chicken chicken, int numTimes) {
for(int i=0; i < numTimes; i++ ) {
chicken.feed();
}
}
/**
* Prompt the user for the chicken's characteristics.
* Create and return a Chicken that has those characteristics.
*
* @param scanner the Scanner from which to get the user input.
* @return the Chicken object that has the characteristics the
* user requested
*/
public static Chicken createChickenWithUser(Scanner scanner) {
System.out.print("What is the name of your chicken? ");
String name = scanner.nextLine();
System.out.print("What is the height of your chicken in cm? ");
int height = scanner.nextInt();
System.out.print("What is the weight of your chicken in lbs? ");
double weight = scanner.nextDouble();
// get the last new line character from the double,
// don't do anything with it.
scanner.nextLine();
return new Chicken(name, height, weight);
}
/**
* Runs the Chicken class.
* If the first command-line argument is "test", runs a test.
* Otherwise, there is a fun chicken feeding game.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
if( args.length > 0 ) {
if( args[0].equals("test") ) {
test();
System.exit(0);
}
}
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
Chicken yourChicken = createChickenWithUser(scanner);
System.out.println("Here's your chicken!");
System.out.println(yourChicken);
// TODO: Refactor code into a new static void method
// called userFeedChicken
System.out.print("Do you want to feed your chicken? (Y/N) ");
String answer = scanner.nextLine();
while( answer.equalsIgnoreCase("Y") ) {
System.out.print("How many times do you want to feed the chicken? (1-3) ");
int numTimes = scanner.nextInt();
feedChicken(yourChicken, numTimes);
scanner.nextLine(); // again, clear out the \n
System.out.println("Here's your chicken! " + yourChicken);
System.out.print("Do you want to feed your chicken again? (Y/N) ");
answer = scanner.nextLine();
}
System.out.println("See you later!");
scanner.close();
}
}
./MathTest.java 4/7
[top][prev][next]
/**
* Demonstrates that you can't construct a Math object.
* This class will not compile.
*
* @author Sara Sprenkle
*/
public class MathTest {
public static void main(String args[]) {
// Compiler displays an error:
// Math() has private access in Math
Math math = new Math();
}
}
./OverloadPlay.java 5/7
[top][prev][next]
/**
* Demonstrates how overloading works (static/compile-time resolution)
* with some dynamic dispatch thrown in.
*
* @author CS209
*/
public class OverloadPlay {
public static void staticPrint(Parent parent) {
System.out.println("Static Parent");
}
public static void staticPrint(Child child) {
System.out.println("Static Child");
}
public void instancePrint(Parent parent) {
System.out.println("Parent");
parent.method();
}
public void instancePrint(Child child) {
System.out.println("Child");
child.method();
}
public static void main(String[] args) {
Child child = new Child();
Parent p = child;
staticPrint(p);
new OverloadPlay().instancePrint(p);
}
}
class Parent {
public void method() {
System.out.println("Called parent's method");
}
}
class Child extends Parent {
public void method() {
System.out.println("Called child's method");
}
}
./TemperatureTable.java 6/7
[top][prev][next]
/**
* Format a table of temperature conversions, using String format
* and System.out.printf
*
* @author CSCI209
*/
public class TemperatureTable {
public static void main(String[] args) {
String headingFormat = "%10s %10s %10s";
String headings = String.format(headingFormat, "Temp C", "Temp F", "Temp K");
String lines = String.format(headingFormat, "------", "------", "------");
System.out.println(headings);
System.out.println(lines);
// Note: it would be better to have the values calculated rather than
// hardcoded, but our focus right now is on formatting.
double[] temps = {-459.7, -273.1, 0.0};
String tempFormat = "%10.1f %10.1f %10.1f";
// Using String.format
System.out.println(String.format(tempFormat, temps[0], temps[1], temps[2]));
// Alternatively: using System.out.printf
// Need to add the \n because printf doesn't automatically add that.
System.out.printf(tempFormat + "\n", temps[0], temps[1], temps[2]);
double[] temps2 = {0.0, -17.8, 255.4};
System.out.println(String.format(tempFormat, temps2[0], temps2[1], temps2[2]));
double[] temps3 = { 32.0, 0.0, 273.1};
System.out.println(String.format(tempFormat, temps3[0], temps3[1], temps3[2]));
// Including \n in the template string
tempFormat = tempFormat + "\n";
System.out.printf(tempFormat, temps3[0], temps3[1], temps3[2]);
}
}
./TemperatureTableStatic.java 7/7
[top][prev][next]
/**
* Format a table of temperature conversions, using String format,
* shown using some static methods and fields
*
* @author CSCI209
*/
public class TemperatureTableStatic {
/** Format of the headings for the table */
private static String headingFormat = "%10s %10s %10s";
/** Format of the data for the table */
private static String tempFormat = "%10.1f %10.1f %10.1f";
/**
* Prints the heading of the temperature table.
*/
public static void printHeading() {
String headings = String.format(headingFormat, "Temp C", "Temp F", "Temp K");
String lines = String.format(headingFormat, "------", "------", "------");
System.out.println(headings);
System.out.println(lines);
}
/**
* Prints the given data in nice format
* param temps an array of 3 temperatures
*/
public static void printData(double[] temps) {
System.out.println(String.format(tempFormat, temps[0], temps[1], temps[2]));
}
public static void main(String[] args) {
// Note: it would be better to have the values calculated rather than
// hardcoded, but our focus right now is on formatting.
double[] temps = {-459.7, -273.1, 0.0};
double[] temps2 = {0.0, -17.8, 255.4};
double[] temps3 = { 32.0, 0.0, 273.1};
printHeading();
printData(temps);
printData(temps2);
printData(temps3);
}
}
Generated by GNU Enscript 1.6.5.90.