Classwork:
New assignments coming up!
Monthly Archives: June 2020
OOD – Pseudocode for your NBody Simulation
Here is a general guide/pseudocode for your OOD N-Body Simulation
Planet ADT
Attributes: x, y, vx, vy, m
Behaviors:
Getter methods(accessors):
one for each attribute
overload toString method
Setter methods (mutators):
one for each attribute
update method with three arguments: mass, x position and y position of another body to calculate the distance between the two bodies, the force between the two bodies, the new velocity in vx and vy components.
position method: to calculate the new x and y coordinates using the updated vx and vy with deltaT
draw method: to “draw” the image
Dynamic System ADT
Attributes: Planet array
Behaviors:
motion method:
Accessor and mutator. It passes the mass, x and y positions from one body to another in the array of planets by using nested “for” loops.
draw method to show new positions
System Simulator “main”:
Set the universe scale
Create each planet and sun (as a planet)
Create array of planets
Create Dynamic System with the array of planets
Optional but pretty useful —> Threads:
while (true) { motion draw try { Thread.sleep(150); } catch (InterruptedException e) { System.out.println("Error sleeping"); } }
OOD Project: NBody Simulation – Animation
OOD – My School: Multi – ADT application – Start Small
/** * Course: ADT for students' courses. * MySchool Application * The Course ADT: * Overload constructor so subject, teacher and period are the input * arguments. * * @RA & mrs.e * @1.8 3/13/2018 & 5/10/19 */ public class Course { private String name; private String period; private String roomNumber; public Course(String name, String period, String roomNumber) { this.name = name; this.period=period; this.roomNumber = roomNumber; } /** * parm name - this is the name of the course */ public String getName() { return name + " "; } // draw course(s) public void draw() { StdDraw.picture(1.5, -1.5, "school_courses.png",1.5,1.5); } /** * this is the period of the class */ public String getPeriod() { return period + " "; } /** * this is the room no of the class */ public String getRoomNumber() { return roomNumber + " "; } public String toString() { String output = "Class name: " + name + "\nRoom Number: " + roomNumber + "\nPeriod: " + period; return output; } }
/** * This is an ADT to represent an abstraction of a student * Student s1 = new Student("Bob", "Smith", 15, "male", 1234);//constructor * @Rida Ahmed & mrs.e * @1.8 3/13/2018 & 5/10/19 */ public class Student { private String firstName; private String lastName; private String age; private String gender; private String id; private Course [] myCourses = new Course [3]; //ADT as an instance field // constructor public Student (String firstName,String lastName,String age,String gender,String id) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.gender = gender; this.id = id; // on hold, not being used } // draw method public void draw() { StdDraw.picture(0.4, 0.5, "school_happykids.png",3.7,2); } // getter methods public String getName () { return firstName + " " + lastName; } public String getPersonalInfo () { return age + ", " + gender + ", " + id; } // setter methods public void setCourses(Course [] courses) { for(int i = 0; i < courses.length; i++){ myCourses[i]=courses[i]; } } public void setACourse (Course aCourse){ //interesting } // overridden method public String toString() { String output = ""; output += "Student name: " + firstName + " " + lastName + "\nCourses: " ; for (int i = 0; i < myCourses.length ; i++) { output += "\n\n" + myCourses[i]; } return output; } }
/** * Customized driver to test all the different parts of my class MySchoolTest: student(s) * * @RA & mrs.e * @1.8 3/13/18 & 5/10/19 */ public class MySchoolTest { public static void main(String [] args) { // set canvas scales StdDraw.setXscale(-2,2); StdDraw.setYscale(-2,2); //create an object of student //then create 3 objects of course //afterwards we add the 3 objects of course to the student Student konoa = new Student("Konoa", "Smith", "15", "female", "1234"); Course c1 = new Course("Biology", "5", "102"); Course c2 = new Course("precalculus", "4", "136"); Course c3 = new Course("APUSH", "7", "117"); // print a course information System.out.println("Print a course "); System.out.println(c1); // add all courses to an array Course [] courses = { c1,c2,c3}; // assign all courses to a student konoa.setCourses(courses); //print a student info and courses System.out.println("\n" + konoa); // draw a student and friends konoa.draw() } } /* * Print a course * Class name: Biology * Room Number: 102 * Period: 5 * Student name: Konoa Smith * Courses: * Class name: Biology * Room Number: 102 * Period: 5 * Class name: precalculus * Room Number: 136 * Period: 4 * Class name: APUSH * Room Number: 117 * Period: 7 * */
/** * Customized driver to test all the different parts of my class MySchoolTest: course(s) * * @RA & mrs.e * @1.8 3/13/18 & 5/10/19 */ public class MySchoolTest { public static void main(String [] args) { // set canvas scales StdDraw.setXscale(-2,2); StdDraw.setYscale(-2,2); //create an object of student //then create 3 objects of course //afterwards we add the 3 objects of course to the student Student konoa = new Student("Konoa", "Smith", "15", "female", "1234"); Course c1 = new Course("Biology", "5", "102"); Course c2 = new Course("precalculus", "4", "136"); Course c3 = new Course("APUSH", "7", "117"); // print a course information System.out.println("Print a course "); System.out.println(c1); // add all courses to an array Course [] courses = { c1,c2,c3}; // assign all courses to a student konoa.setCourses(courses); c1.draw(); } }
OOD Project: My Application
Programming Project: My Application
Write your own application based on a set of interacting objects.
Here are some ideas keeping in mind a simplified system and yet a good testing class. Your test class must include activities between the objects and their methods.
Requirements for the project:
1. Methods must be consistent: toSTring(), getter and setter methods.
2. Encapsulation must be enforced. All instance fields should be private.
3. Objects from different ADTs must interact with each other.
4. The test driver must execute all parts of the implementation.
Advice:
1. Keep it simple. You can add more after it runs successfully. You can keep the big picture in mind but develop from small components.
2. Start with just two ADT objects just like in My School example. First start with Student and Course objects only.
https://java.mrseliasclasses.org/my-school-how-to-implement-a-multi-adt-application-ood/
Later, we add Teacher and after that add the School ADT. Example will be provided shortly.
https://java.mrseliasclasses.org/my-school-multi-adt-application-ood-add-more/
3. The test driver should be the final version of the many changes and additions you made as you develop your full application.
In this version of your project, submit two ADTs and a test driver with minimal activity between the object(s) of each ADT.
Grade notes:
If your ADTs have only String objects and primitive data types as instance fields, the best grade you can get is a 65.
If your ADTs do not interact with each other, the best grade you can get is a 65.
If you only have 2 ADTs interacting with each other, the best grade you can get is a 80. Optimal number of interacting ADTs is 3.
1. A good description of your project – Tell the story about your application and make sure the story clearly identifies the objects you create from the different ADTs.
2. Author’s name
3. Date and java version
4. Include the output from the your test driver
5. The test driver should have enough activity to test all methods from each ADT
OOD – Cell Mitosis w/StdDraw
You have already written an ADT, Cell_YI with the instance fields, the attributes which identify all the different components in a cell. In this assignment, you will add a new feature, the draw methods using StdDraw.
Before you get started, think about how you are going to break up the images to show the different phases of the mitosis.
Here are some of the resources you can use for the Cell Mitosis and other animations/simulations: 3 Options:
-Take a cell image and using an image editor make the components of the cell separate images.
-Using multiple images and compile them into an array of “frames”
/************************************************************************* * Compilation: javac Duke.java * Execution: java Duke * Dependencies: StdDraw.java StdIn.java * * Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. * Last updated: Wed Feb 9 09:02:07 EST 2011. * * * Draw the sequence of images T1.gif to T17.gif. This creates * the illusion of motion, where the Java mascot Duke cart-wheels * across the screen. * * Reference: http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#TumbleItem * *************************************************************************/ public class Duke { public static void main(String[] args) { int images = 17; // number of images int WIDTH = 130, HEIGHT = 80; // images are 130-by-80 StdDraw.setCanvasSize(WIDTH, HEIGHT); StdDraw.setXscale(0, WIDTH); StdDraw.setYscale(0, HEIGHT); // main animation loop for (int t = 0; true; t++) { int i = 1 + (t % images); String filename = "T" + i + ".gif"; // name of the ith image StdDraw.picture(WIDTH/2.0, HEIGHT/2.0, filename); StdDraw.show(); StdDraw.pause(100); } } }
-Make your own images by drawing them with an app like the one attached. This will allow you to manipulate the individual components of the cell easier and it will have a fluent transformation. It will look pixelated but that is not a bad thing at all.
https://www.piskelapp.com/
If you need to scale pictures, you can use this method from StdDraw:
/** Draws the specified image centered at (x, y), rescaled to the specified bounding box. The supported image formats are JPEG, PNG, and GIF. @param x the center x-coordinate of the image @param y the center y-coordinate of the image @param filename the name of the image/picture, e.g., "ball.gif" @param scaledWidth the width of the scaled image (in screen coordinates) @param scaledHeight the height of the scaled image (in screen coordinates) @throws IllegalArgumentException if either {@code scaledWidth} or {@code scaledHeight} is negative @throws IllegalArgumentException if the image filename is invalid */ public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight)
/******************************************************************************
* Compilation: javac BouncingBallDeluxe.java
* Execution: java BouncingBallDeluxe
* Dependencies: StdDraw.java StdAudio.java
* https://introcs.cs.princeton.edu/java/15inout/TennisBall.png
* https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
*
* Implementation of a bouncing tennis ball in the box from (-1, -1) to (1, 1),
* with sound effects.
*
* % java BouncingBallDeluxe
*
******************************************************************************/
public class BouncingBallDeluxe {
public static void main(String[] args) {
// initial values
double rx = 0.480, ry = 0.860; // position
double vx = 0.015, vy = 0.023; // velocity
double radius = 0.05; // radius
// set the scale of the coordinate system
StdDraw.setXscale(-1.0, 1.0);
StdDraw.setYscale(-1.0, 1.0);
StdDraw.enableDoubleBuffering();
// main animation loop
while (true) {
// bounce off wall according to law of elastic collision
if (Math.abs(rx + vx) + radius > 1.0) {
vx = -vx;
}
if (Math.abs(ry + vy) + radius > 1.0) {
vy = -vy;
}
// update position
rx = rx + vx;
ry = ry + vy;
// set the background to light gray
StdDraw.clear(StdDraw.LIGHT_GRAY);
// draw ball on the screen
StdDraw.picture(rx, ry, "TennisBall.png");
// display and pause for 20ms
StdDraw.show();
StdDraw.pause(20);
}
}
}
/** * Turning a functional program to an ADT application. * * @GE * @java 1.8 date: 1/18/19 */ public class Ball { private double rx = 0.480, ry = 0.860; // position private double vx = 0.015, vy = 0.023; // velocity private double radius = 0.05; public double rx() { return rx; } public double ry() { return ry; } public void setRx(double rx) { this.rx = rx; } public void setRy(double ry) { this.ry = ry; } public double[] getVel() { double [] vel = { vx, vy}; return vel; } public void setVx(double vx) { this.vx = vx; } public void setVy(double vy) { this.vy = vy; } public double radius() { return radius; } }
/****************************************************************************** * * Implementation of a bouncing tennis ball in the box from (-1, -1) to (1, 1), * with sound effects. * * % java BouncingBallODD * ******************************************************************************/ public class BouncingBallOOD { public static void main(String[] args) { Ball bouncy = new Ball(); // set the scale of the coordinate system StdDraw.setXscale(-1.0, 1.0); StdDraw.setYscale(-1.0, 1.0); StdDraw.enableDoubleBuffering(); // main animation loop while (true) { // bounce off wall according to law of elastic collision if (Math.abs(bouncy.rx() + bouncy.getVel()[0]) + bouncy.radius() > 1.0) { bouncy.setVx(-bouncy.getVel()[0]); } if (Math.abs(bouncy.ry() + bouncy.getVel()[1]) + bouncy.radius() > 1.0) { bouncy.setVy(-bouncy.getVel()[1]); } // update position bouncy.setRx(bouncy.rx() + bouncy.getVel()[0]); bouncy.setRy(bouncy.ry() + bouncy.getVel()[1]); // set the background to light gray StdDraw.clear(StdDraw.LIGHT_GRAY); // draw ball on the screen StdDraw.picture(bouncy.rx(), bouncy.ry(), "TennisBall.png"); // display and pause for 20ms StdDraw.show(); StdDraw.pause(20); } } }
Cell Mitosis – OOD
What is cell mitosis? In cell biology, mitosis (/maɪˈtoʊsɪs/) is a part of the cell cycle when replicated chromosomes are separated into two new nuclei. https://en.wikipedia.org/wiki/Mitosis
Write an ADT, Cell_YI with the instance fields, the attributes which identify all the different components in a cell and with the purpose of illustrating (with text only) the activity of mitosis in the driver or test class.
Remember what an abstraction is! It is a simplified version or a real thing. In your assignment, you need to simplify the process in cell mitosis and yet the general idea must not be lost. This is an open assignment that would allow you to develop your skills not just as a programmer, also as a designer.
Write the test driver, CellMitosisTest_YI.java, to simulate the mitosis of a cell. This simulation is not visual. It is text-based. Since it is text-based, be clear in your messages when describing each step of the mitosis and how it takes place. It should describe the process of cell mitosis.
Your methods, behaviors have to be clearly defined and well documented. A well-designed ADT has behaviors that return a string so printing takes place in the driver. Your output should be understood by anyone who wants to learn about Cell Mitosis in a biology class at PHS.
The images below are examples of how detail you want the abstraction can be.
OOD NBody Simulation Computations
Some extra help
Calculate for each body in the system and every other body:
- distance square = (x distance between itself and the other body)^2 + (y distance between itself and the other body)^2
- force = G * its mass * the other’s mass / distance^2
- forceX = force * (the other’s x position – its x position )/ distance
- forceY = force * (the other’s y position – its y position )/ distance
- accelerationX = forceX / its mass
- accelerationY = forceY / its mass
- velocityX += deltaT * accelerationX
- velocityY += deltaT * accelerationY
update the new position for the body
- x position += deltaT * velocityX
- y position += deltaT * velocityY
OOD: Shannon Entropy
Classwork/Homework:
These assignments are to be developed using the basic elements of object oriented design.
Generating cryptograms. A cryptogram is obtained by scrambling English text by replacing each letter with another letter. Write a program, YI_Crypto1.java to generate a random permutation of the 26 letters and use this to map letters. Give example: Don’t scramble punctuation or whitespace.
Entropy. The Shannon entropy measures the information content of an input string and plays a cornerstone role in information theory and data compression.
Shannon is famous for having founded information theory.
It was proposed by Claude Shannon in 1948, borrowing upon the concept in statistical thermodynamics. Assuming each character i appears with probability p(_{i}), the entropy is defined to be H = – sum p(_{i}) log(_{2})p(_{i}), where the contribution is 0 if p(_{i}) = 0. Compute entropy of DNA sequence.
(a) Write a program, YI_Entropy1.java to read in a ASCII text string from standard input, count the number of times each ASCII character occurs, and compute the entropy, assuming each character appears with the given probabilities.
(b) Repeat part (a) but use Unicode.
OOD: Advanced topic: The “this” operator
Designing classes
The this operator
Make sure you read thoroughly.
1. Make the following changes to the BankAccount class:
a. Include a print statement in the getBalance() method to show the reference to the implicit parameter. Include “from method getBalance”
b. Include a print statement in both constructors, “from method default constructor” and “from constructor with parameter”.
2. Implement a test class, ThisOperatorTest. In this test, create an object of the class BankAccount and print it.
3. Include a commented paragraph at the end of the test class making a conclusion on the output. Make sure you explain what the this operator does in the two programs and compare them.
4. The following questions refer to calling by reference, by value and side effects:
• Modify your BankAccount class to include a new method, transfer. This method has two input parameters, double amount and double otherBalance from a different BankAccount object. The method takes money from the calling object’s balance and increases the balance from the other object by the “amount” value. The method also includes two print statements to display each object.
System.out.println(“From transfer( ), current object @: ” + _missing parameter);
System.out.println(“From transfer( ), otherAccount @: ” + otherBalance);
Create a test class, BankAccountTest1. In main:
• Create two BankAccount objects.
• Display the balance from both objects.
• Call the transfer method from one object to transfer money to the other object’s balance.
• Display both accounts’ balance.
A different approach to the same idea in 4:
• Modify your BankAccount class to include a new method, transfer. This method has two input parameters, double amount and BankAccount otherAccount. The method takes money from the calling object’s balance and increases the otherAccount’s balance by the “amount” value. The method also includes two print statements to display each object.
System.out.println(“From transfer( ), current object @: ” + _missing parameter);
System.out.println(“From transfer( ), otherAccount @: ” + otherAccount);
Look at edmodo.com for the different posts and due dates.