Category Archives: Classwork

Input/Output: Animations: Ballistic Motion I

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:
Projectile motion with drag. Use the supplied program and make the necessary changes to show during the animation the following:
Ballistic Motion Sim

Projectile motion with drag. Write a program YI_BallisticMotion1.java that plots the trajectory of a ball that is shot with velocity v at an angle theta. Account for gravitational and drag forces. Assume that the drag force is proportional to the square of the velocity. Using Newton’s equations of motions and the Euler-Cromer method, update the position, velocity, and acceleration according to the following equations:

Use the given program to enhance it to show the image bellow:
1. The values should change as the ball travels through the air.
2. The values should move with the ball.
3. The blue text and dotted curve is not included in the GUI.

project motion math

[spoiler title=’BallisticMotion.java’]

/******************************************************************************
* Compilation: javac BallisticMotion.java
* Execution: java BallisticMotion v theta
* Dependencies: StdDraw.java
*
* Simluate the motion of a ball fired with velocity v at theta degrees
* with coefficient of drag C. Uses Euler-Cramer method to numerically
* solve differential equation.
*
* % java BallisticMotion 180.0 60.0
*
* % java BallisticMotion 20.0 45.0
* Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.
* Last updated: Mon Aug 3 12:15:11 EDT 2015.
******************************************************************************/

public class BallisticMotion {

public static void main(String[] args) {
double G = 9.8; // gravitational constant m/s^2
double C = 0.002; // drag force coefficient

double v = Double.parseDouble(args[0]); // velocity
double theta = Math.toRadians(Double.parseDouble(args[1])); // angle in radians

double x = 0.0, y = 0.0; // position
double vx = v * Math.cos(theta); // velocity in x direction
double vy = v * Math.sin(theta); // velocity in y direction

double ax = 0.0, ay = 0.0; // acceleration
double t = 0.0; // time
double dt = 0.01; // time quantum

double maxR = v*v / G; // maximum distance without drag force
StdDraw.setXscale(0, maxR);
StdDraw.setYscale(0, maxR); // set the same as for X-scale

// loop until ball hits ground
while (y >= 0.0) {
v = Math.sqrt(vx*vx + vy*vy);
ax = -C * v * vx;
ay = -G – C * v * vy;
vx += ax * dt;
vy += ay * dt;
x += vx * dt;
y += vy * dt;StdDraw.filledCircle(x, y, 0.25);
StdDraw.show();
StdDraw.pause(5);
StdDraw.clear();

}

StdDraw.show();
}

}

[/spoiler]

Homework:
Work on the ballistic motion assignment.

OOD: BlueJ House

January 13th, 2015

Classwork:
Using BlueJ’s video notes and source files on edmodo.com, create a new picture where there are more than one person in different locations, a house, a sun and grass.

Screen Shot 2015-01-13 at 10.07.43 AM

If you don’t remember exactly how it was done, the video links are on yesterday’s post.

Homework:
6. Implement a class Employee. An employee has a name (a string) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a small program that tests your class.

OOD – Java and BlueJ Videos


OOD – Refresher
Java Video Tutorial 7


Chapter 3: VN 3.1 Fields of class types


Chapter 3: VN 3.2 Constructors and field initialization


Chapter 3: VN 3.3 Solving the 12-hour clock exercise

Look into edmodo.com for assignments and due date

Homework:
Watch this video:

If you are moving ahead:
Screen Shot 2015-02-02 at 10.03.46 AM

Use these libraries, download StdIn.java, StdOut.java, StdDraw.java, and StdAudio.java
Look at Standard output and input.
Redirection and piping.
Standard drawing.
Standard audio.
Graphical user interfaces.
Look at exercises 1 through 9 and work on exercise 10. Submit it to edmodo.com.

OOD Challenge Exercise

Chapter 1: VN 1.4 Solving a challenge exercise

Exercise 1:
Add a sunset to the single-sun version of Picture. That is: make the sun go
down slowly. Remember: The circle has a method slowMoveVertical
that you can use to do this.

Exercise 2: If you added your sunset to the end of the draw
method (so that the sun goes down automatically when the picture is
drawn), change this now. We now want the sunset in a separate method,
so that we can call draw and see the picture with the sun up, and then
call sunset (a separate method!) to make the sun go down.

You will find this code:
private Square wall;

private Square window;

private Triangle roof;

private Circle sun;

You need to add a line here for the second sun,

For example: private Circle sun2;

Then write the appropriate code for creating the second sun.

Exercise 3: Close the picture project, and open the lab-classes project.
This project is a simplified part of a student database designed to keep track of students in laboratory classes and to print class lists.
Create an object of class Student. You will notice that this time you
are not only prompted for a name of the instance, but also for some
other parameters. Fill them in before clicking Ok. (Remember that
parameters of type String must be written in double-quotes.)

OOD A Class Anatomy

OOD1
OOD2
OOD4
OOD5
OOD6
OOD7
OOD8
OOD9
OOD10
OOD11
OOD12

An ADT: Greeter

public class Greeter
{
   public String sayHello()
   {
      String message = "Hello, World!";
      return message;
   }
}

The tester class also called the driver:

public class GreeterTest
{
   public static void main(String[] args)
   {
      Greeter worldGreeter = new Greeter();
      System.out.println(worldGreeter.sayHello());
   }
}

An ADT: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

The driver class:

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

Assignments:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD: Car ADT

A class that defines an object with instance fields (attributes) and methods(behaviors) is called an ADT: Abstract Data Type

What is an abstraction?
Can you give an example of an abstraction?

“An abstraction is a general concept or idea, rather than something concrete or tangible. In computer science, abstraction has a similar definition. It is a simplified version of something technical, such as a function or an object in a program. The goal of “abstracting” data is to reduce complexity by removing unnecessary information.”
https://techterms.com/definition/abstraction

Implement a class Car_YI with the following properties.

  • A car has a certain fuel efficiency (measured in miles/gallon or liters/km—pick one) and a certain amount of fuel in the gas tank.
  • The efficiency is specified in the constructor, and the initial fuel level is 0.
  • Supply a method drive that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and methods getGas, returning the current fuel level, and addGas, to tank up.

Sample driver/test class:

Car_YI myBeemer = new Car_YI(29); // 29 miles per gallon 
myBeemer.addGas(20); // tank 20 gallons
myBeemer.drive(100); // drive 100 miles 
System.out.println(myBeemer.getGas()); // print fuel remaining


OOD – SavingsAccount

What to turn in when you submit your work in edmodo.com:
* a. Copy and paste both programs
* b. Attach both files
* c. Output should be included in your tester/driver class as a comment
* d. Test all your code: Think of data that will force execution of all the lines of code.

Classwork:
Write a class SavingsAccount_YI that is similar to the BankAccount class, except that it has an added instance variable interest. Supply a constructor that sets both the initial balance and the interest rate. Supply a method addInterest (with no explicit parameter) that adds interest to the account. Write a tester/driver program that constructs a savings account with an initial balance of $1,000 and interest rate 10%. Then apply the addInterest method five times and print the resulting balance.

bank

OOD: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.

  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”

  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.

  4. Add a method

void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD: Pre conditions – Person

bug report
xkcd
Assignments:
1. Enhance the BetterBankAccount_YI class by adding preconditions
For the constructor: require the amount parameter to be at least zero
For the deposit method: require the amount parameter to be at least zero
For the withdraw method: the amount to be a value between 0 and the current balance

Driver: Write enough code in the tester class to invoke (call) all the methods.
Atm machines.

  1. Write a class Person with the following specifications:

a. Constructor: it takes a name as a string, a second string argument that describes what member of the family it is and, a third string describing the member activity to create a short story. You can make any changes you feel is necessary to accomplish this.

b. Mutator Method: setAge(int anAge). It prompts the user for age and updates the class instance field.

c. Mutator Method: setWhatIamDoing(String doing). It prompts the user and updates the class instance field currentActivity. Keep the number of activities low so it doesn’t become too lengthly.

d. Accessor Method: getWhatIamDoing(). It displays the currentActivity.

Tester class: MyFamilyDriver.java

despicableme2

Create or “instantiate” 4 persons, a mother, a father, a son or a daughter and a friend.
Simulate the following set of events:
The mother keeps milk in the refrigerator.
The father keeps juice in the refrigerator.
The son keeps a can of soda in the refrigerator.
The friend is thirsty and wants to drink something.

This is a story about “encapsulation” so your ending must reflect this concept. Be creative and use your imagination. The lines above is only an example. Do not use it for your own story. You can add more methods and instance fields to the Person ADT so you can make the simulation work nicely.

Some java language help:
String a = “abc”;
String b = “abcdefg”;
System.out.println(b.contains(a)); // true