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

 * 
 */
Konoa and friends
/**
 * 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 biologymitosis (/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

planetarysys

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.

crypto

Entropy. The Shannon entropy measures the information content of an input string and plays a cornerstone role in information theory and data compression.

Screen Shot 2015-05-05 at 8.21.45 PM            Shannon Entropy Calculator

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.

entropy1

Screen Shot 2015-05-25 at 1.40.56 AM

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.

OOD Project: gpa calculator

Classwork:
Write a program, YI_GPACalculator.java to read grades from a text file. The grades will have a specific structure so the marking periods, the subjects, and categories can be identified.

The file structure given here is just an example. You should notice it has some redundancy. You can configure your own structure to enable easier implementation.

[spoiler title=’gpadata.txt’]
Q1
Subject: English
Categories start:
Homework: .30
Classwork: .30
Test: .40
Categories end
Data:
Homework:
75
90
85
Classwork:
65
75
78
Test:
100
98
99
Subject: Math
Categories start:
Homework: .25
Classwork: .25
Test: .50
Categories end
Data:
Homework:
86
88
100
Classwork:
60
70
80
Test:
100
90
91
Q1 end
Q2
Subject: English
Categories start:
Homework: .30
Classwork: .30
Test: .40
Categories end
Data:
Homework:
95
80
81
Classwork:
55
95
88
Test:
93
100
85
Subject: Math
Categories start:
Homework: .25
Classwork: .25
Test: .50
Categories end:
Homework:
86
88
100
Classwork:
60
70
80
Test:
87
96
81
Q2 end
[/spoiler]

Here is some code that might help you read the file.

  1. Using PU libraries: StdIn.java
/**
 * Calculate the GPA given a file with all the requirements.
 * Q1
 * Subject: English
 * Categories start:
 * Homework: .30
 * Classwork:
 * ....
 * ....
 * END
 * 
 * java GPACalculator1 < gpadata.txt
 * 
 */
public class GPACalculator1
{
    public static void main(String [] args)
    {

            while (StdIn.hasNextLine()) {
                String s1 = StdIn.readLine();
                System.out.println(s1);
            }
          
    
    }
    
}

  1. Using java libraries:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
 * Calculate the GPA given a file with all the requirements.
 * Subject: English
 * Catgories beginning:
 * 
 */
public class GPACalculator2
{
    public static void main(String [] args)
    {
        
        File file = new File(args[0]);
    
        try {
    
            Scanner sc = new Scanner(file);
    
            while (sc.hasNextLine()) {
                String s1 = sc.nextLine();
                System.out.println(s1);
            }
            sc.close();
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    
    }
    
}

Before you get started writing code,
1. Draft a flowchart or a concise pseudocode.
2. Trace few grades from one subject for Q1 and Q2.
3. Manually calculate the GPA for the data used in the trace.
4. Confirm that your trace and calculation coincide.

Submit all your work to edmodo.com.

OOD – Colliding Balls Simulation

Follow these steps:

  1. Download the attached BlueJ project file, Collision.zip to your java folder. Double click on it.
  2. Open the folder and double-click the BlueJ package icon.
  3. Replace “_YI” suffix with your initials in all the files that use it.
  4. Study the code for the Ball_YI, BallDriver_YI, and CollidingBall_YI classes.
  5. Modify the Ball_YI class as follows:
    — a. When any ball collides with another, the ball changes direction. Their behavior after the collision is up to you but it has to be noticeable. There are two types of collisions, elastic and inelastic. It is also up to you to choose the type.
    — b. When any ball collides with each other, the ball changes to a random color and stays that color until it collides again.
    — c. When any ball collides with the walls, the ball changes to a random color. NOTE: It is ok if all the balls change color at the same time.

    Submission:
  6. A short QuickTime video.
  7. Attach Ball_YI, and CollidingBall_YI classes.

Collision Detection:

 These diagram should help you with the calculations for the conditions you need to implement to capture the the balls within a “d” distance of each other:

   or

More Hints: look at the problem from the cartessian plane perspective:

OOD: ArrayList – Intro

/**
 * Test of ArrayLists basic instructions
 * 
 * @ge
 * @4/16/18
 */
import java.util.ArrayList;

public class ArrayListTest
{
   public static void main(String [] args)
   {
        
       ArrayList myList = new ArrayList();
       //ArrayList myList = new ArrayList(); // more efficient - eliminates warning
       Integer x = new Integer(45); // creates Integer 45
       
       myList.add(x); // adds Integer 45 to myList
       myList.remove(x); // removes the value 45 from myList
       x = new Integer(100); // creates Integer 100 
       myList.add(0,x); // adds Integer 100 to the beginning of myList

       System.out.println(myList.get(0)); // print the first element 
       System.out.println(myList.size()); // print the number of elements
       
       // One step further
       myList.add(5);
       myList.add(-27);
       myList.add(55);
       myList.add(0,3);
   }
}

Classwork:

Let’s use the following documentation Java™ Platform, Standard Edition 8
API Specification to create our own resources: 

ArrayList

From the documentation copy and paste the following methods’ description:

* 1
* boolean add(E e)
*
* 2
* void add(int index, E element)

* Having two methods with the same name but different argument list
* is called OVERLOADING
*
* 3
* E get(int index)
*
* 4
* E set(int index, E element)
*
* 5
* int indexOf(Object o)
*
* 6
* boolean isEmpty()
* Returns true if this list contains no elements.
*
* 7
* E remove(int index)
*
* 8
* boolean remove(Object o)
*
* 9
* int size()

Resource:
Screen Shot 2016-01-15 at 7.46.11 AM

Assignment:
ArrayListBasics_YI.java
Write a program that does the following:
Choose a meaningful and complete message for each item in the list.

  1. It creates an ArrayList, anAList of 100 random integers between any values from 1 to 1000 and find the two consecutive integers with the smallest difference between the two of them.

  2. It finds and prints with a message the largest value in anAList.

  3. It finds and prints with a message the average value in anAList.

  4. It prints all the numbers from anAList separated with a space and in one line.

  5. It prints the numbers from anAlist separated by 3 spaces in 10 columns by 10 rows format. Use printf to achieve this format. Do not use tab: “\t”.

  6. Prompt the user for an integer and replace the 10th Integer with this new one. Display a message to acknowledge wether it was found.

  7. Prompt the user for a number and search for that number. Display the number and the index where it was found.

  8. Remove 10th Integer and print a message with the number.

  9. Print the number of elements the ArrayList anAlist contains.

Note: Use printf to keep all your numbers tab properly.

/**** Make sure your documentation includes the output ****/