4.1.6: Using the Rectangle Class
//RectangleTester.java
public class RectangleTester extends ConsoleProgram
{
public void run()
{
// Create a rectangle with width 5 and height 12
Rectangle rect = new Rectangle(5, 12);
// Then print it out
System.out.println(rect);
}
}
//Rectangle.java
public class Rectangle
{
private int width;
private int height;
public Rectangle(int rectWidth, int rectHeight)
{
width = rectWidth;
height = rectHeight;
}
public int getArea()
{
return width * height;
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public String toString()
{
return "Rectangle with width: " + width + " and height: " + height;
}
}
4.1.7: Calling a Method
public class RectangleTester extends ConsoleProgram
{
public void run()
{
// Create a rectangle with width 7 and height 14
Rectangle rect = new Rectangle(7, 14);
// Print out the height
System.out.println(rect.getHeight());
// Print out the width
System.out.println(rect.getWidth());
// Print out the area by calling the getArea method
System.out.println(rect.getArea());
}
}
public class Rectangle
{
private int width;
private int height;
public Rectangle(int rectWidth, int rectHeight)
{
width = rectWidth;
height = rectHeight;
}
public int getArea()
{
return width * height;
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public String toString()
{
return "Rectangle with width: " + width + " and height: " + height;
}
}
4.1.8: Using the Point Class
public class Point
{
private int x;
private int y;
public Point(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
public void move(int dx, int dy)
{
x += dx;
y += dy;
}
public String toString()
{
return x + ", " + y;
}
}
public class PointTester extends ConsoleProgram
{
public void run()
{
Point p = new Point(10, 5);
System.out.println(p);
p.move(3, 4);
System.out.println(p);
// Make a new point here at position (2, 4)
Point p2 = new Point(2, 4);
// Then print it out
System.out.println(p2);
}
}
4.1.9: Using the Student Class
public class StudentTester extends ConsoleProgram
{
public void run()
{
Student alan = new Student("Alan", "Turing", 11);
Student ada = new Student("Ada", "Lovelace", 12);
// Add an entry for yourself here!
Student studentName = new Student("First name", "Last name", 10);
System.out.println(alan);
System.out.println(ada);
// Print out your student object
System.out.println(studentName);
}
}
public class Student
{
private String firstName;
private String lastName;
private int gradeLevel;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
4.2.5: Text Messages
public class TextMessage
{
private String message;
private String sender;
private String receiver;
public TextMessage(String from, String to, String theMessage)
{
sender = from;
receiver = to;
message = theMessage;
}
public String toString()
{
return sender + " texted " + receiver + ": " + message;
}
}
public class Messages extends ConsoleProgram
{
public void run()
{
// Your code here.
TextMessage t1 = new TextMessage(
"Bart", "Lisa", "Where are you?"
);
TextMessage t2 = new TextMessage(
"Lisa", "Bart", "I'm at school!"
);
// Create the two TextMessage objects and print them out.
System.out.println(t1);
System.out.println(t2);
}
}
4.3.5: Coin Flips
import java.util.*;
public class Randomizer{
public static Random theInstance = null;
public Randomizer(){
}
public static Random getInstance(){
if(theInstance == null){
theInstance = new Random();
}
return theInstance;
}
public static boolean nextBoolean(){
return Randomizer.getInstance().nextBoolean();
}
public static boolean nextBoolean(double probability){
return Randomizer.nextDouble() < probability;
}
public static int nextInt(){
return Randomizer.getInstance().nextInt();
}
public static int nextInt(int n){
return Randomizer.getInstance().nextInt(n);
}
/* Return a nubmer between min and max, inclusive. */
public static int nextInt(int min, int max){
return min + Randomizer.nextInt(max - min + 1);
}
public static double nextDouble(){
return Randomizer.getInstance().nextDouble();
}
public static double nextDouble(double min, double max){
return min + (max - min) * Randomizer.nextDouble();
}
}
public class CoinFlips extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int heads = 0;
int tails = 0;
for(int i = 0; i < FLIPS; i++)
{
if(Randomizer.nextBoolean())
{
System.out.println("Heads");
heads++;
}
else
{
System.out.println("Tails");
tails++;
}
}
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
System.out.println("% Heads: " + heads / (double)FLIPS);
System.out.println("% Tails: " + tails / (double)FLIPS);
}
}
4.3.6: Longest Streak
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int longestStreak = 0;
int curStreak = 0;
for(int i = 0; i < FLIPS; i++)
{
Boolean flip = Randomizer.nextBoolean();
if (flip)
{
System.out.println("Heads");
curStreak++;
if (curStreak > longestStreak)
{
longestStreak = curStreak;
}
}
else
{
System.out.println("Tails");
curStreak = 0;
}
}
System.out.println("Longest streak of heads: " + longestStreak);
}
}
import java.util.*;
public class Randomizer{
public static Random theInstance = null;
public Randomizer(){
}
public static Random getInstance(){
if(theInstance == null){
theInstance = new Random();
}
return theInstance;
}
public static boolean nextBoolean(){
return Randomizer.getInstance().nextBoolean();
}
public static boolean nextBoolean(double probability){
return Randomizer.nextDouble() < probability;
}
public static int nextInt(){
return Randomizer.getInstance().nextInt();
}
public static int nextInt(int n){
return Randomizer.getInstance().nextInt(n);
}
/* Return a nubmer between min and max, inclusive. */
public static int nextInt(int min, int max){
return min + Randomizer.nextInt(max - min + 1);
}
public static double nextDouble(){
return Randomizer.getInstance().nextDouble();
}
public static double nextDouble(double min, double max){
return min + (max - min) * Randomizer.nextDouble();
}
}
4.3.8: How Far Away is…?
/*
* This class stores information about a location on Earth. Locations are
* specified using latitude and longitude. The class includes a method for
* computing the distance between two locations.
*
* This implementation is based off of the example from Stuart Reges at
* the University of Washington.
*/
public class GeoLocation
{
// Earth radius in miles
public static final double RADIUS = 3963.1676;
private double latitude;
private double longitude;
/**
* Constructs a geo location object with given latitude and longitude
*/
public GeoLocation(double theLatitude, double theLongitude)
{
latitude = theLatitude;
longitude = theLongitude;
}
/**
* Returns the latitude of this geo location
*/
public double getLatitude()
{
return latitude;
}
/**
* returns the longitude of this geo location
*/
public double getLongitude()
{
return longitude;
}
// returns a string representation of this geo location
public String toString()
{
return "latitude: " + latitude + ", longitude: " + longitude;
}
// returns the distance in miles between this geo location and the given
// other geo location
public double distanceFrom(GeoLocation other)
{
double lat1 = Math.toRadians(latitude);
double long1 = Math.toRadians(longitude);
double lat2 = Math.toRadians(other.latitude);
double long2 = Math.toRadians(other.longitude);
// apply the spherical law of cosines with a triangle composed of the
// two locations and the north pole
double theCos = Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(long1 - long2);
double arcLength = Math.acos(theCos);
return arcLength * RADIUS;
}
}
public class HowFarAway extends ConsoleProgram
{
public void run()
{
double firstLat = readDouble("Enter the latitude of the starting location: ");
double firstLong = readDouble("Enter the longitude of the starting location: ");
double secondLat = readDouble("Enter the latitude of the ending location: ");
double secondLong = readDouble("Enter the longitude of the ending location: ");
GeoLocation firstLoc = new GeoLocation(firstLat,firstLong);
GeoLocation secondLoc = new GeoLocation(secondLat,secondLong);
double distance = firstLoc.distanceFrom(secondLoc);
System.out.println("The distance is " + distance + " miles.");
}
}
4.4.5: Triangle Class: Constructor
public class TriangleTester extends ConsoleProgram
{
public void run()
{
// Write the Triangle constructor in the Triangle class
// and test out creating new Triangle objects here!
// For example:
Triangle testTriangle = new Triangle(5, 3);
System.out.println(testTriangle);
}
}
public class Triangle
{
private double height;
private double width;
public Triangle(double triWidth, double triHeight)
{
width = triWidth;
height = triHeight;
}
public String toString()
{
return "Triangle with width: " + width + " and height: " + height;
}
}
4.4.8: toString for Flowers
public class Flower
{
private String name;
private String color;
private String genus;
private String species;
public Flower(String theName, String theColor, String theGenus, String theSpecies)
{
name = theName;
color = theColor;
genus = theGenus;
species = theSpecies;
}
public String toString()
{
return color + " " + name + " (" + genus + " " + species + ")";
}
}
public class FlowerTester extends ConsoleProgram
{
public void run()
{
Flower foxglove = new Flower("Foxglove", "Red", "Digitalis", "obscura");
System.out.println(foxglove);
}
}
4.4.9: Instance Variables for Your Dog
public class Dog
{
private String breed;
private String name;
public Dog(String theBreed, String theName)
{
breed = theBreed;
name = theName;
}
public String toString()
{
return name + " is a " + breed;
}
}
public class DogTester extends ConsoleProgram
{
public void run()
{
Dog golden = new Dog("Golden Retriever", "Sammy");
System.out.println(golden);
}
}
4.4.10: Student GPA Field
public class StudentTester extends ConsoleProgram
{
public void run()
{
Student alan = new Student("Alan", "Turing", 11, 3.5);
Student ada = new Student("Ada", "Lovelace", 12, 3.8);
System.out.println(alan);
System.out.println(ada);
}
}
public class Student
{
private String firstName;
private String lastName;
private int gradeLevel;
// Add your instance variable here.
private double gpa;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade, double gradePointAverage)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
gpa = gradePointAverage;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel + " and has GPA: " + gpa;
}
}
4.4.12: Pizza Time!
public class Pizza
{
private String type;
private String toppings;
private int size;
public Pizza(String theType, String theToppings, int theSize)
{
type = theType;
toppings = theToppings;
size = theSize;
}
public String toString()
{
return size + " inch " + type + " pizza with " + toppings;
}
}
public class PizzaTester extends ConsoleProgram
{
public void run()
{
// Test your Pizza class here.
Pizza pizza1 = new Pizza("Veggie", "Tomatoes, onions, olives", 12);
Pizza pizza2 = new Pizza("Cheese", "Cheese", 15);
Pizza pizza3 = new Pizza("Meat", "Pepperoni, sausage, bacon", 20);
System.out.println(pizza1);
System.out.println(pizza2);
System.out.println(pizza3);
}
}
⚠ 4.4.13: Fractions ⚠
public class FractionTester extends ConsoleProgram
{
public void run()
{
// ⚠ Students can create their own tests here for their Fraction class
}
}
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int thisNumerator, int thisDenominator)
{
numerator = thisNumerator;
denominator = thisDenominator;
}
public String toString()
{
return numerator + "/" + denominator;
}
}
4.5.5: Writing getPerimeter()
public class RectangleTester extends ConsoleProgram
{
public void run()
{
// Create and test Rectangle objects here!
}
}
public class Rectangle
{
private int width;
private int height;
public Rectangle(int rectWidth, int rectHeight)
{
width = rectWidth;
height = rectHeight;
}
public int getArea()
{
return width * height;
}
public int getPerimeter()
{
return 2 * width + 2 * height;
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public String toString()
{
return "Rectangle with width: " + width + " and height: " + height;
}
}
4.5.6: Honors Students
public class StudentTester extends ConsoleProgram
{
public void run()
{
Student alan = new Student("Alan", "Turing", 11);
alan.setGPA(3.5);
Student ada = new Student("Ada", "Lovelace", 12);
ada.setGPA(3.8);
System.out.println(alan);
System.out.println(ada);
System.out.println(alan.isHonorsStudent());
}
}
public class Student
{
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public boolean isHonorsStudent()
{
return gpa >= 3.5;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
4.5.7: The Full Triangle Class
public class TriangleTester extends ConsoleProgram
{
public void run()
{
// Create and test out Triangle objects here!
}
}
public class Triangle
{
private int height;
private int width;
public Triangle(int triWidth, int triHeight)
{
width = triWidth;
height = triHeight;
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public double getArea()
{
return (.5 * width * height);
}
}
4.5.8: Batting Average
public class BaseballTester extends ConsoleProgram
{
public void run()
{
BaseballPlayer babeRuth = new BaseballPlayer("Babe Ruth", 2873, 8399);
System.out.println(babeRuth);
System.out.println(babeRuth.getBattingAverage());
}
}
public class BaseballPlayer
{
private int hits;
private int atBats;
private String name;
public BaseballPlayer(String theName, int theHits, int theAtBats)
{
name = theName;
hits = theHits;
atBats = theAtBats;
}
public String toString()
{
return name + ": " + hits + "/" + atBats;
}
public double getBattingAverage()
{
return (double) hits / atBats;
}
}
⚠ 4.5.9: Distance in Kilometers ⚠
/*
* This class stores information about a location on Earth. Locations are
* specified using latitude and longitude. The class includes a method for
* computing the distance between two locations.
*
* This implementation is based off of the example from Stuart Reges at
* the University of Washington.
*/
public class GeoLocation
{
// Earth radius in miles
public static final double RADIUS = 3963.1676;
// Number of kilomteres in one mile
public static final double KM_PER_MILE = 1.60934;
private double latitude;
private double longitude;
/**
* Constructs a geo location object with given latitude and longitude
*/
public GeoLocation(double theLatitude, double theLongitude)
{
latitude = theLatitude;
longitude = theLongitude;
}
/**
* Returns the latitude of this geo location
*/
public double getLatitude()
{
return latitude;
}
/**
* returns the longitude of this geo location
*/
public double getLongitude()
{
return longitude;
}
// returns a string representation of this geo location
public String toString()
{
return "latitude: " + latitude + ", longitude: " + longitude;
}
public double distanceFromInKilometers(GeoLocation other)
{
// fill this in.
return distanceFrom(other) * KM_PER_MILE;
}
// returns the distance in miles between this geo location and the given
// other geo location
public double distanceFrom(GeoLocation other)
{
double lat1 = Math.toRadians(latitude);
double long1 = Math.toRadians(longitude);
double lat2 = Math.toRadians(other.latitude);
double long2 = Math.toRadians(other.longitude);
// apply the spherical law of cosines with a triangle composed of the
// two locations and the north pole
double theCos = Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(long1 - long2);
double arcLength = Math.acos(theCos);
return arcLength * RADIUS;
}
}
public class DistanceTester extends ConsoleProgram
{
public static double SAN_FRANCISCO_LONGITUDE = 122.4167;
public static double SAN_FRANCISCO_LATITUDE = 37.7833;
public static double NEW_YORK_LONGITUDE = 74.0059;
public static double NEW_YORK_LATITUDE = 40.7127;
/**
* This program computes the distance in miles between San Francisco, California
* and New York City, New York using the GeoLocation class.
*
* After running this program, try looking it up on Google Maps. How close are we?
*/
public void run()
{
GeoLocation sf = new GeoLocation(SAN_FRANCISCO_LATITUDE, SAN_FRANCISCO_LONGITUDE);
GeoLocation nyc = new GeoLocation(NEW_YORK_LATITUDE, NEW_YORK_LONGITUDE);
double distance = sf.distanceFromInKilometers(nyc);
System.out.println("The distance from San Francisco to New York is " + distance + " kilometers");
}
}
4.6.5: Text Messages Gather Methods
public class TextMessage
{
private String message;
private String sender;
private String receiver;
public TextMessage(String from, String to, String theMessage)
{
sender = from;
receiver = to;
message = theMessage;
}
public String getSender()
{
return sender;
}
public String getReceiver()
{
return receiver;
}
public String getMessage()
{
return message;
}
public String toString()
{
return sender + " texted " + receiver + ": " + message;
}
}
public class Messages extends ConsoleProgram
{
public void run()
{
// Your code here.
// Create the two TextMessage objects and print them out.
TextMessage message1 = new TextMessage("Ada", "Alan", "Hey! How is it going?");
TextMessage message2 = new TextMessage("Alan", "Ada", "Pretty good how are you?");
System.out.println(message1);
System.out.println(message2);
}
}
4.6.6: Fractions Getter/Setter Methods
public class FractionTester extends ConsoleProgram
{
public void run()
{
// Add code here to test out your Fraction class!
}
}
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int num, int denom)
{
numerator = num;
denominator = denom;
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int x)
{
numerator = x;
}
public void setDenominator(int x)
{
denominator = x;
}
public String toString()
{
return numerator + "/" + denominator;
}
}
4.6.7: Full Fraction Class
public class FractionTester extends ConsoleProgram
{
public void run()
{
// Add code here to test out your Fraction class!
}
}
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int num, int denom) {
numerator = num;
denominator = denom;
}
public int getNumerator(){
return this.numerator;
}
public int getDenominator(){
return denominator;
}
public void add(Fraction other) {
numerator = numerator * other.getDenominator() + other.getNumerator() * denominator;
denominator = denominator * other.getDenominator();
}
public void subtract(Fraction other) {
numerator = numerator * other.getDenominator() - other.getNumerator() * denominator;
denominator = denominator * other.getDenominator();
}
public void multiply(Fraction other) {
numerator = numerator * other.getNumerator();
denominator = denominator * other.getDenominator();
}
public String toString() {
return numerator + " / " + denominator;
}
}
4.7.7: The Unit Circle
public class UnitCircle extends ConsoleProgram
{
public void run()
{
System.out.println("Radians: (cos, sin)");
for (double i = 0; i < 2*Math.PI; i += (Math.PI / 4))
{
double angle = Math.round(i * 100) / 100.0;
double cos = Math.cos(angle);
double sin = Math.sin(angle);
cos = Math.round(cos * 100) / 100.0;
sin = Math.round(sin * 100) / 100.0;
String output = "" + angle + ": " + cos + ", " + sin;
System.out.println(output);
}
}
}
4.7.8: How Many Players in the Game?
public class Player
{
// Static Variables
public static int totalPlayers = 0;
public static int maxPlayers = 10;
// Public Methods
public Player()
{
totalPlayers++;
}
// Static Methods
public static boolean gameFull()
{
return totalPlayers >= maxPlayers;
}
}
4.7.9: Circle Area, another way
public class Circle
{
private static final double PI = 3.14159265359;
private double radius;
public Circle(double theRadius)
{
radius = theRadius;
}
// Change the implementation of this method.
public double getArea()
{
return PI * Math.pow(radius, 2);
}
}
4.7.10: Rock, Paper, Scissors: Get Winner
private String getWinner(String user, String computer)
{
String USER_PLAYER = "User wins!";
String COMPUTER_PLAYER = "Computer wins!";
String TIE = "Tie";
if(user.equals(computer))
{
return TIE;
}
if(user.equals("rock") && computer.equals("paper"))
{
return COMPUTER_PLAYER;
}
if(user.equals("rock") && computer.equals("scissors"))
{
return USER_PLAYER;
}
if(user.equals("paper") && computer.equals("rock"))
{
return USER_PLAYER;
}
if(user.equals("paper") && computer.equals("scissors"))
{
return COMPUTER_PLAYER;
}
if(user.equals("scissors") && computer.equals("rock"))
{
return COMPUTER_PLAYER;
}
return USER_PLAYER;
}
4.7.11: Rock, Paper, Scissors!
public class RockPaperScissors extends ConsoleProgram
{
private static final String USER_PLAYER = "User wins!";
private static final String COMPUTER_PLAYER = "Computer wins!";
private static final String TIE = "Tie";
/**
* Function: getWinner
*
* Parameters:
* String user - a string holding the choice that the user player
* made. Must either be "rock", "paper", or "scissors"
* String computer - a string holding the choice that the computer
* player made. Must either be "rock", "paper", or "scissors"
*
* Determines the winner based on the rules of rock paper scissors.
* Rock beats scissors and loses to paper
* Paper beats rock and loses to scissors
* Scissors beats paper and loses to rock
* Identical choices tie
*
* Return: a string holding a message describing the winner, either
* USER_PLAYER, COMPUTER_PLAYER, or TIE
*/
private String getWinner(String user, String computer)
{
if(user.equals(computer))
{
return TIE;
}
if(user.equals("rock") && computer.equals("paper"))
{
return COMPUTER_PLAYER;
}
if(user.equals("rock") && computer.equals("scissors"))
{
return USER_PLAYER;
}
if(user.equals("paper") && computer.equals("rock"))
{
return USER_PLAYER;
}
if(user.equals("paper") && computer.equals("scissors"))
{
return COMPUTER_PLAYER;
}
if(user.equals("scissors") && computer.equals("rock"))
{
return COMPUTER_PLAYER;
}
return USER_PLAYER;
}
public void run()
{
while(true){
//Get the user's choice
String choice = readLine("Enter your choice (rock, paper, or scissors): ");
choice = choice.toLowerCase();
//End the game if the user entered a blank line
if(choice.equals("")){
break;
}
//Make sure it was a valid choice
if(choice.equals("rock") || choice.equals("paper") || choice.equals("scissors")){
//Print the user choice
System.out.println("User: " + choice);
//Get the computer random choice
String[] compChoices = new String[]{"rock", "paper", "scissors"};
int compChoiceNum = Randomizer.nextInt(0, 2);
String compChoice = compChoices[compChoiceNum];
//Print the computer choice
System.out.println("Computer: " + compChoice);
//Print the winner
System.out.println(getWinner(choice, compChoice));
}
else{
System.out.println(choice + "is not a valid move. Please try again");
}
}
//End the game with a nice message
System.out.println("Thanks for playing!");
}
}
4.8.5: Product Method Overloading
public class Product extends ConsoleProgram
{
public void run()
{
int intValue = 5;
double doubleValue = 2.5;
int product1 = product(intValue, intValue);
System.out.println(product1);
// Use method overloading to define methods
// for each of the following method calls
double product2 = product(doubleValue, doubleValue);
System.out.println(product2);
int product3 = product(intValue, intValue, intValue);
System.out.println(product3);
double product4 = product(intValue, doubleValue);
System.out.println(product4);
double product5 = product(doubleValue, intValue);
System.out.println(product5);
double product6 = product(doubleValue, doubleValue, doubleValue);
System.out.println(product6);
}
public int product(int one, int two)
{
return one * two;
}
public double product(double one, double two)
{
return one * two;
}
public int product(int one, int two, int three)
{
return one * two * three;
}
public double product(int one, double two)
{
return one * two;
}
public double product(double one, int two)
{
return one * two;
}
public double product(double one, double two, double three)
{
return one * two * three;
}
}
4.9.6: Which Variables Exist?
public class MathOperations extends ConsoleProgram
{
private double PI = 3.14159;
public void run()
{
int sumResult = sum(5, 10);
int differenceResult = difference(20, 2);
double productResult = product(3.5, 2);
double circumferenceResult = circleCircumference(10);
double areaResult = circleArea(12);
}
public int sum(int one, int two)
{
// Printing Variables Example
System.out.println("PI: " + PI);
System.out.println("one: " + one);
System.out.println("two: " + two);
return one + two;
}
public int difference(int one, int two)
{
// PRINT OUT VARIABLES HERE
System.out.println("PI: " + PI);
System.out.println("one: " + one);
System.out.println("two: " + two);
return one - two;
}
public double product(double a, double b)
{
double result = a * b;
// PRINT OUT VARIABLES HERE
System.out.println("PI: " + PI);
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("result: " + result);
return result;
}
public double circleCircumference(int radius)
{
// PRINT OUT VARIABLES HERE
System.out.println("PI: " + PI);
System.out.println("radius: " + radius);
return 2 * radius * PI;
}
public double circleArea(int radius)
{
double area = PI * radius * radius;
// PRINT OUT VARIABLES HERE
System.out.println("PI: " + PI);
System.out.println("radius: " + radius);
System.out.println("area: " + area);
return area;
}
}
4.10.4: Batteries - Needs to be Redone
public class BatteryTester extends ConsoleProgram
{
public void run()
{
Battery aaBattery1 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery2 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery3 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
Battery aaBattery4 = new Battery(1.5);
System.out.println("Total voltage: " + Battery.totalVoltage);
System.out.println("Total batteries: " + Battery.numOfBatteries);
}
}
public class Battery
{
private double voltage;
public static double totalVoltage = 0;
public static int numOfBatteries = 0;
public Battery(double voltage)
{
this.voltage = voltage;
totalVoltage += voltage;
numOfBatteries += 1;
}
public double getVoltage()
{
return this.voltage;
}
}
4.10.5: Write Your Own CodeHS
public class ExerciseTester extends ConsoleProgram
{
public void run()
{
Exercise exercise1 = new Exercise();
Exercise exercise2 = new Exercise("Who needs this anyways?", "Java", 9001);
System.out.println(exercise1.getTitle());
System.out.println(exercise2.getTitle());
}
}
public class Exercise
{
public String title = "JavaScript Exercise";
public String programmingLanguage = "JavaScript";
public int points = 100;
// Default constructor.
public Exercise()
{
}
// Edit code in this constructor.
public Exercise(String title, String programmingLanguage, int points)
{
this.title = title;
this.programmingLanguage = programmingLanguage;
this.points = points;
}
public String getTitle() {
return title;
}
}
4.11.7: Comparing Circles
public class CircleTester extends ConsoleProgram
{
public void run()
{
Circle one = new Circle(10, "blue", 50, 35);
Circle two = new Circle(10, "blue", 50, 35);
Circle three = new Circle(20, "red", 0, 0);
Circle four = three;
if(one.equals(two))
{
System.out.println("Circles one and two are equal!");
System.out.println(one);
System.out.println(two);
}
if(three.equals(four))
{
System.out.println("Circles three and four are equal!");
System.out.println(three);
System.out.println(four);
}
}
}
public class Circle
{
private int radius;
private String color;
private int x;
private int y;
public Circle(int theRadius, String theColor, int xPosition, int yPosition)
{
radius = theRadius;
color = theColor;
x = xPosition;
y = yPosition;
}
public int getRadius()
{
return radius;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public String getColor()
{
return color;
}
public String toString()
{
return color + " circle with a radius of " + radius + " at position (" + x + ", " + y + ")";
}
public boolean equals(Circle other)
{
return color.equals(other.getColor()) && radius == other.getRadius() && x == other.getX() && y == other.getY();
}
}
4.12.4: Clothing Store
public class TShirt extends Clothing
{
private String fabric;
public TShirt(String size, String color, String fabric)
{
super(size, color);
this.fabric = fabric;
}
public String getFabric()
{
return fabric;
}
}
public class ClothingTester extends ConsoleProgram
{
public void run()
{
String size;
String color;
size = readLine("What size T-Shirt? ");
color = readLine("What color is it? ");
String fabric = readLine("What kind of fabric is it? ");
TShirt tShirt = new TShirt(size, color, fabric);
size = readLine("What size sweatshirt? ");
color = readLine("What color is it? ");
boolean hooded = readBoolean("Does it have a hood? ");
Sweatshirt sweatShirt = new Sweatshirt(size, color, hooded);
size = readLine("What size jeans? ");
Jeans jeans = new Jeans(size);
System.out.println("You want a " + tShirt.getSize() + " "
+ tShirt.getFabric() + " t-shirt in " + tShirt.getColor() + ".");
if (sweatShirt.hasHood())
{
System.out.println("And a " + sweatShirt.getSize() + " "
+ sweatShirt.getColor() + " hooded sweatshirt.");
} else {
System.out.println("And a " + sweatShirt.getSize() + " "
+ sweatShirt.getColor() + " sweatshirt.");
}
System.out.println("Also, " + jeans.getSize() + " " + jeans.getColor()
+ " jeans.");
}
}
public class Clothing
{
private String size;
private String color;
public Clothing (String size, String color)
{
this.size = size;
this.color = color;
}
public String getSize()
{
return size;
}
public String getColor()
{
return color;
}
}
public class Sweatshirt extends Clothing
{
private boolean hooded;
public Sweatshirt(String size, String color, boolean hooded)
{
super(size, color);
this.hooded = hooded;
}
public boolean hasHood()
{
return hooded;
}
}
public class Jeans extends Clothing
{
public Jeans(String size)
{
super(size, "blue");
}
}
4.13.5: Finding the Perimeters
Note: Multi-tiered Section
public class Square extends Rectangle
{
public Square(double sideLength)
{
super("Square", sideLength, sideLength);
}
public double getSideLength()
{
return super.getHeight();
}
}
public abstract class Shape
{
private String name;
public Shape(String name)
{
this.name = name;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public abstract double getArea();
public abstract double getPerimeter();
}
public class Rectangle extends Shape
{
private double width;
private double height;
public Rectangle(String name, double width, double height)
{
super(name);
this.width = width;
this.height = height;
}
public Rectangle(double width, double height)
{
this("Rectangle", width, height);
}
public double getArea()
{
return width * height;
}
public double getPerimeter()
{
return 2 * (width + height);
}
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public String toString()
{
return "Rectangle with width: " + width + " and height: " + height;
}
}
public class ShapesTester extends ConsoleProgram
{
public void run()
{
Shape rectangle = new Rectangle(10, 20);
System.out.println("Name: " + rectangle.getName());
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());
System.out.println();
Shape r2 = new Rectangle(5, 10);
System.out.println("Name: " + r2.getName());
System.out.println("Area: " + r2.getArea());
System.out.println("Perimeter: " + r2.getPerimeter());
System.out.println();
Shape circle = new Circle(10);
System.out.println("Name: " + circle.getName());
System.out.println("Area: " + circle.getArea());
System.out.println("Perimeter: " + circle.getPerimeter());
System.out.println();
Shape square = new Square(6);
System.out.println("Name: " + square.getName());
System.out.println("Area: " + square.getArea());
System.out.println("Perimeter: " + square.getPerimeter());
System.out.println();
Shape pentagon = new Pentagon(5);
System.out.println("Name: " + pentagon.getName());
System.out.println("Area: " + pentagon.getArea());
System.out.println("Perimeter: " + pentagon.getPerimeter());
System.out.println();
}
}
public class Pentagon extends Shape
{
private double sideLength;
public Pentagon(String name, double sideLength)
{
super(name);
this.sideLength = sideLength;
}
public Pentagon(double sideLength)
{
this("Pentagon", sideLength);
}
public double getSideLength()
{
return sideLength;
}
public double getArea()
{
return 1.0 / 4.0 * Math.sqrt(5.0 * (5.0 + 2.0 * Math.sqrt(5.0)))
* Math.pow(sideLength, 2);
}
public double getPerimeter()
{
return 5.0 * sideLength;
}
}
public class Circle extends Shape
{
private double radius;
public Circle(String name, double radius)
{
super(name);
this.radius = radius;
}
public Circle(double radius)
{
this("Circle", radius);
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return Math.PI * Math.pow(radius, 2);
}
public double getPerimeter()
{
return 2.0 * Math.PI * radius;
}
}
4.14.5: Fun with Solids
import java.lang.Math;
public class Pyramid extends Solid
{
private double length;
private double width;
private double height;
public Pyramid(String name, double l, double w, double h)
{
super(name);
length = l;
width = w;
height = h;
}
public double volume()
{
return length * width * height / 3.0;
}
public double surfaceArea()
{
return length * width + length * Math.sqrt(Math.pow(width / 2.0, 2) +
Math.pow(height, 2)) + width * Math.sqrt(Math.pow(length / 2.0, 2) +
Math.pow(height, 2));
}
}
import java.lang.Math;
public class Sphere extends Solid
{
private double radius;
public Sphere(String name, double radius)
{
super(name);
this.radius = radius;
}
public double volume()
{
return (4.0/3.0) * Math.PI * Math.pow(this.radius, 3);
}
public double surfaceArea()
{
return 4.0 * Math.PI * Math.pow(this.radius, 2);
}
}
public class RectangularPrism extends Solid
{
private double length;
private double width;
private double height;
public RectangularPrism(String name, double l, double w, double h)
{
super(name);
length = l;
width = w;
height = h;
}
public double volume()
{
return length * width * height;
}
public double surfaceArea()
{
return 2 * (length * width + width * height + length * height);
}
}
public abstract class Solid
{
private String name;
public Solid(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public abstract double volume();
public abstract double surfaceArea();
}
public class SolidTester
{
public static void main(String[] args)
{
String name;
double volume;
double surfaceArea;
Pyramid pyramid = new Pyramid("My pyramid", 1, 3, 5);
name = pyramid.getName();
volume = round(pyramid.volume(), 2);
surfaceArea = round(pyramid.surfaceArea(), 2);
System.out.println("Pyramid '" + name + "' has volume: " + volume +
" and surface area: " + surfaceArea + ".");
Sphere sphere = new Sphere("My sphere", 4);
name = sphere.getName();
volume = round(sphere.volume(), 2);
surfaceArea = round(sphere.surfaceArea(), 2);
System.out.println("Sphere '" + name + "' has volume: " + volume +
" and surface area: " + surfaceArea + ".");
RectangularPrism rectangularPrism = new RectangularPrism("My rectangular prism",
5, 8, 3);
name = rectangularPrism.getName();
volume = round(rectangularPrism.volume(), 2);
surfaceArea = round(rectangularPrism.surfaceArea(), 2);
System.out.println("RectangularPrism '" + name + "' has volume: " +
volume + " and surface area: " + surfaceArea + ".");
Cylinder cylinder = new Cylinder("My cylinder", 4, 9);
name = cylinder.getName();
volume = round(cylinder.volume(), 2);
surfaceArea = round(cylinder.surfaceArea(), 2);
System.out.println("Cylinder '" + name + "' has volume: " + volume +
" and surface area: " + surfaceArea + ".");
Cube cube = new Cube("My cube", 4);
name = cube.getName();
volume = round(cube.volume(), 2);
surfaceArea = round(cube.surfaceArea(), 2);
System.out.println("Cube '" + name + "' has volume: " + volume +
" and surface area: " + surfaceArea + ".");
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
}
public class Cube extends RectangularPrism
{
public Cube(String name, double side)
{
super(name, side, side, side);
}
}
import java.lang.Math;
public class Cylinder extends Solid
{
private double radius;
private double height;
public Cylinder(String name, double radius, double height)
{
super(name);
this.radius = radius;
this.height = height;
}
public double volume()
{
return Math.PI * Math.pow(radius, 2) * height;
}
public double surfaceArea()
{
return 2 * Math.PI * radius * (radius + height);
}
}
4.15.5: Fraction is Comparable
public class Fraction implements Comparable<Fraction>
{
private int numerator;
private int denominator;
public Fraction(int numer, int denom)
{
numerator = numer;
denominator = denom;
}
public void add(Fraction other)
{
numerator = numerator * other.getDenominator() +
other.getNumerator() * denominator;
denominator *= other.getDenominator();
}
public void subtract(Fraction other)
{
numerator = numerator * other.getDenominator() -
other.getNumerator() * denominator;
denominator *= other.getDenominator();
}
public void multiply(Fraction other)
{
numerator *= other.getNumerator();
denominator *= other.getDenominator();
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int x)
{
numerator = x;
}
public void setDenominator(int x)
{
denominator = x;
}
public String toString()
{
return numerator + "/" + denominator;
}
public int compareTo(Fraction other)
{
int diff = this.numerator * other.getDenominator() - other.getNumerator() * this.denominator;
if(diff > 0)
{
return 1;
}
else if (diff < 0)
{
return -1;
}
else
{
return 0;
}
}
public boolean equals(Object other)
{
return other instanceof Fraction && compareTo((Fraction)other) == 0;
}
}
4.15.6: City is Summable
public class City implements Summable
{
private int population;
private String name;
public City(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getValue()
{
return this.population;
}
public int add(Summable other)
{
return getValue() + other.getValue();
}
}
Practice Quiz
Our practice test will include a pluthera of practice problems.
Practice Quiz
The practice quiz will be only be available for an extremely limited time. The practice quiz is delayed and will be released 12 hours before the actual quiz. For your own safety, the practice quiz will be closed when lunch ends.
Disclaimer
Please note, our code will be removed 48 hours prior to when it is due. Copying our code and redistributing it is strictly prohitbited. If another document is found, Chingar Docs will be shut down until the external source is removed permanently.
Support
If you find any code that does not work, please do it yourself and send it to us.