Category Archives: Assignment

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 – 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: BallDriver and CollidingBalls Videos

BallDriver Video #1
A short video for Ball and BallDriver – Looking at the geometry behind the relative distance between 2 balls.
Oops: I meant radius.

BallDriver Video #2
Going over the first changes we did to the original code.

BallDriver Video #3
Integrating the geometry into the implementation to have a better way to determine the distance apart from a pair of balls.

BallDriver Video #4
Overloading
A quick look at two constructors for the same class.

BallDriver Video #5
Ball ADT and BallDriver Complete
This is the final version of the BallDriver assignment. The important concept to learn is how accessor methods are used to get information from the input argument which is an object of the Ball ADT. This illustrates ENCAPSULATION since instance fields are private and public methods are needed to get access to their values.

BallDriver Video #6
Last video and final implementation (no color)

BallDriver Video #7
Code for color changing of the balls

BallDriver Video #8
Putting color in the BallDriver assignment.

CollidingBalls Video #9
Overloading Trick

How to make a short video of your animations using QuickTime

OOD Project: LFSR by steps

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

REMINDER: Ms. Newman should be coming to PHS after school

  1. Simulate one step. The step() method simulates one step of the LFSR and returns the rightmost bit as an integer (0 or 1). For example,
// LFSR lfsr1 = new LFSR("01101000010", 9);
// for this assignment the seed and tap can be hardcoded or input
String lfsr1 = "01101000010";
int tap = 9;
StdOut.println(lfsr1);
for (int i = 0; i < 10; i++) {
    // int bit = lfsr1.step();
    // code to create a sequence of 0s and 1s like the example below
    StdOut.println(lfsr1 + " " + bit);
}

outputs
01101000010
11010000101 1
10100001011 1
01000010110 0
10000101100 0
00001011001 1
00010110010 0
00101100100 0
01011001001 1
10110010010 0
01100100100 0

  1. Extracting multiple bits. The method generate() takes a positive integer k as an argument and returns a k-bit integer obtained by simulating k steps of the LFSR. This task is easy to accomplish with a little arithmetic:
  • initialize a variable to zero
  • for each bit extracted, double the variable
  • add the bit returned by step()

For example, extracting (from left to right) each bit from the sequence 1 1 0 0 1, the variable takes on the values 1, 3, 6, 12, and 25, ending with the binary representation of the bit sequence.

gen = 0
gen = gen * 2 + new_bit = 0 * 2 + 1 = 1
gen = gen * 2 + new_bit = 1 * 2 + 1 = 3
gen = gen * 2 + new_bit = 3 * 2 + 0 = 6
gen = gen * 2 + new_bit = 6 * 2 + 0 = 12
gen = gen * 2 + new_bit = 12 * 2 + 1 = 25

For example,

// LFSR lfsr2 = new LFSR("01101000010", 9); 
// for this assignment the seed and tap can be hardcoded or input
String lfsr2 = "01101000010";
int tap = 9;
StdOut.println(lfsr2);
for (int i = 0; i < 10; i++) {
    // int r = lfsr2.generate(5);
    // code to generate a number like 25 in the example above
    StdOut.println(lfsr2 + " " + r);
}

outputs
01101000010
00001011001 25
01100100100 4
10010011110 30
01111011011 27
01101110010 18
11001011010 26
01101011100 28
01110011000 24
01100010111 23
01011111101 29

Classwork:
Write a java program, YI_LFSRSim.java to generate an output like the one right above for a given seed.
NOTE: It doesn’t have to be OOP.

OOD Project: LFSR Assignment

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

[spoiler title=’Picture.java’]

import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;


/**
 *  This class provides methods for manipulating individual pixels of
 *  an image. The original image can be read from a .jpg, .gif,
 *  or .png file or the user can create a blank image of a given size.
 *  This class includes methods for displaying the image in a window on
 *  the screen or saving it to a file.
 *
  • Pixel (x, y) is column x and row y. * By default, the origin (0, 0) is upper left, which is a common convention * in image processing. * The method setOriginLowerLeft() change the origin to the lower left. *

  • For additional documentation, see * Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class Picture implements ActionListener { private BufferedImage image; // the rasterized image private JFrame frame; // on-screen view private String filename; // name of file private boolean isOriginUpperLeft = true; // location of origin private final int width, height; // width and height /** * Initializes a blank width-by-height picture, with width columns * and height rows, where each pixel is black. * * @param width the width of the picture * @param height the height of the picture */ public Picture(int width, int height) { if (width < 0) throw new IllegalArgumentException(“width must be nonnegative”); if (height < 0) throw new IllegalArgumentException(“height must be nonnegative”); this.width = width; this.height = height; image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // set to TYPE_INT_ARGB to support transparency filename = width + “-by-” + height; } /** * Initializes a new picture that is a deep copy of the argument picture. * * @param picture the picture to copy */ public Picture(Picture picture) { width = picture.width(); height = picture.height(); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); filename = picture.filename; for (int col = 0; col < width(); col++) for (int row = 0; row < height(); row++) image.setRGB(col, row, picture.get(col, row).getRGB()); } /** * Initializes a picture by reading from a file or URL. * * @param filename the name of the file (.png, .gif, or .jpg) or URL. */ public Picture(String filename) { this.filename = filename; try { // try to read from file in working directory File file = new File(filename); if (file.isFile()) { image = ImageIO.read(file); } // now try to read from file in same directory as this .class file else { URL url = getClass().getResource(filename); if (url == null) { url = new URL(filename); } image = ImageIO.read(url); } if (image == null) { throw new IllegalArgumentException(“Invalid image file: ” + filename); } width = image.getWidth(null); height = image.getHeight(null); } catch (IOException e) { // e.printStackTrace(); throw new RuntimeException(“Could not open file: ” + filename); } } /** * Initializes a picture by reading in a .png, .gif, or .jpg from a file. * * @param file the file */ public Picture(File file) { try { image = ImageIO.read(file); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(“Could not open file: ” + file); } if (image == null) { throw new RuntimeException(“Invalid image file: ” + file); } width = image.getWidth(null); height = image.getHeight(null); filename = file.getName(); } /** * Returns a JLabel containing this picture, for embedding in a JPanel, * JFrame or other GUI widget. * * @return the JLabel */ public JLabel getJLabel() { if (image == null) return null; // no image available ImageIcon icon = new ImageIcon(image); return new JLabel(icon); } /** * Sets the origin to be the upper left pixel. This is the default. */ public void setOriginUpperLeft() { isOriginUpperLeft = true; } /** * Sets the origin to be the lower left pixel. */ public void setOriginLowerLeft() { isOriginUpperLeft = false; } /** * Displays the picture in a window on the screen. */ public void show() { // create the GUI for viewing the image if needed if (frame == null) { frame = new JFrame(); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu(“File”); menuBar.add(menu); JMenuItem menuItem1 = new JMenuItem(” Save… “); menuItem1.addActionListener(this); menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(menuItem1); frame.setJMenuBar(menuBar); frame.setContentPane(getJLabel()); // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setTitle(filename); frame.setResizable(false); frame.pack(); frame.setVisible(true); } // draw frame.repaint(); } /** * Returns the height of the picture. * * @return the height of the picture (in pixels) */ public int height() { return height; } /** * Returns the width of the picture. * * @return the width of the picture (in pixels) */ public int width() { return width; } /** * Returns the color of pixel (col, row). * * @param col the column index * @param row the row index * @return the color of pixel (col, row) * @throws IndexOutOfBoundsException unless both 0 ≤ col < width * and 0 ≤ row < height */ public Color get(int col, int row) { if (col < 0 || col >= width()) throw new IndexOutOfBoundsException(“col must be between 0 and ” + (width()-1) + “: ” + col); if (row < 0 || row >= height()) throw new IndexOutOfBoundsException(“row must be between 0 and ” + (height()-1) + “: ” + col); if (isOriginUpperLeft) return new Color(image.getRGB(col, row)); else return new Color(image.getRGB(col, height – row – 1)); } /** * Sets the color of pixel (col, row) to given color. * * @param col the column index * @param row the row index * @param color the color * @throws IndexOutOfBoundsException unless both 0 ≤ col < width * and 0 ≤ row < height * @throws NullPointerException if color is null */ public void set(int col, int row, Color color) { if (col < 0 || col >= width()) throw new IndexOutOfBoundsException(“col must be between 0 and ” + (width()-1) + “: ” + col); if (row < 0 || row >= height()) throw new IndexOutOfBoundsException(“row must be between 0 and ” + (height()-1) + “: ” + row); if (color == null) throw new NullPointerException(“can’t set Color to null”); if (isOriginUpperLeft) image.setRGB(col, row, color.getRGB()); else image.setRGB(col, height – row – 1, color.getRGB()); } /** * Returns true if this picture is equal to the argument picture. * * @param other the other picture * @return true if this picture is the same dimension as other * and if all pixels have the same color; false otherwise */ public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Picture that = (Picture) other; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int col = 0; col < width(); col++) for (int row = 0; row < height(); row++) if (!this.get(col, row).equals(that.get(col, row))) return false; return true; } /** * This operation is not supported because pictures are mutable. * * @return does not return a value * @throws UnsupportedOperationException if called */ public int hashCode() { throw new UnsupportedOperationException(“hashCode() is not supported because pictures are mutable”); } /** * Saves the picture to a file in a standard image format. * The filetype must be .png or .jpg. * * @param name the name of the file */ public void save(String name) { save(new File(name)); } /** * Saves the picture to a file in a PNG or JPEG image format. * * @param file the file */ public void save(File file) { filename = file.getName(); if (frame != null) frame.setTitle(filename); String suffix = filename.substring(filename.lastIndexOf(‘.’) + 1); suffix = suffix.toLowerCase(); if (suffix.equals(“jpg”) || suffix.equals(“png”)) { try { ImageIO.write(image, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println(“Error: filename must end in .jpg or .png”); } } /** * Opens a save dialog box when the user selects “Save As” from the menu. */ @Override public void actionPerformed(ActionEvent e) { FileDialog chooser = new FileDialog(frame, “Use a .png or .jpg extension”, FileDialog.SAVE); chooser.setVisible(true); if (chooser.getFile() != null) { save(chooser.getDirectory() + File.separator + chooser.getFile()); } } /** * Unit tests this Picture data type. * Reads a picture specified by the command-line argument, * and shows it in a window on the screen. */ public static void main(String[] args) { Picture picture = new Picture(args[0]); System.out.printf(“%d-by-%d\n”, picture.width(), picture.height()); picture.show(); } }

[/spoiler]

Write a java program, YI_Pixels30x30.java to display the RGB colors of the top area of the image in this format:

R     G    B
196   200  105
155   0    50
...

OOD: Dodge Ball Game Videos

Dodge Game Video #1
Project Setup

Dodge Game Video #2
Mouse Follower

Dodge Game Video #3
Simple Weighted Attraction

Dodge Game Video #4
Dodge Game Spring Moti

Dodge Ball video #5
Changing the MouseFollower into an ADT part 1 of 2

Dodge Ball video #6
Changing the MouseFollower into an ADT part 2 of 2

Dodge Ball video #7
Player and CollidingBalls integrated into the driver, DodgeGame (1 of 2)

Dodge Ball video #8
Player and CollidingBalls integrated into the driver, DodgeGame (2 of 2)

How to make a short video of your animations using QuickTime

Mail Order System

Good programming style:

  1. Header (Description, author’s name, date, and java version)
  2. Imports if any.
  3. Driver or tester class.
  4. The program should have a proper exit with a message.
  5. Input/output included as a paragraph comment.

The following description of this assignment can be modified to suit the requirements: it should use at least an ArrayList, it should be object-oriented, and have good programming practices. 

mail-order house sells five products whose retail prices are as follows:

Product 1, $2.98

Product 2, $4.50

Product 3, $9.98

Product 4, $4.49

Product 5, $6.87

Write a java program MailOrder_YI.java and its driver, MailOrderTest.java to prompt the user for the following after a short welcome message.

a) Product number
b) Quantity sold


It should calculate and display the total retail value of all products sold. Use a sentinel-controlled (like “yesNo”) loop to determine when the program should stop looping and display the final results.


Sample output:

Welcome to Mrs. “Elia’s Mail Order Clearing House”
Product 1, $2.98
Product 2, $4.50
Product 3, $9.98
Product 4, $4.49
Product 5, $6.87

Product number?: 1
Quantity?: 2
Do you want to continue?(yes/no): yes
Product number?: 2
Quantity?: 5
Do you want to continue?(yes/no): yes
Product number?: 3
Quantity?: 3
Do you want to continue?(yes/no): yes
Product number?: 4
Quantity?: 1
Do you want to continue?(yes/no): no
Total Price: $62

Required submission:

  1. A short video.
  2. Copy and paste both programs.
  3. Submit the zipped project.

Calories and Fat Calculator

Good programming style:

  1. Header (Description, author’s name, date, and java version)
  2. Imports if any.
  3. Driver or tester class.
  4. The program should have a proper exit with a message.
  5. Input/output included as a paragraph comment.

The following description of this assignment can be modified to suit the requirements: it should use at least an ArrayList, it should be object-oriented, and have good programming practices. 

Write a java program, FoodChart.java, and FoodChartTest.java to provide calories and fat content in a selected number of foods.
– Choose 4 different categories of foods from the link attached to the image or any other resource you might want to use.
– Write a function for each of the categories with at least 5 food choices.
– Display a menu and prompt the user for choices.
– Once the user is finished selecting, display the number of calories and the fat content.

Example:

1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category: 2

1. Rice, brown long-grain  Fat: 1.8 grams Calories: 216
2. Pasta, whole wheat      Fat: 1 gram    Calories: 214
3. Pasta, corn             Fat: 1.5 grams Calories: 210
4. Pasta, Quinoa           Fat: 0 grams   Calories: 200
5. Pasta, Soba (buckwheat) Fat: 1.5 grams Calories: 190
Choose the food: 4

Do you want to continue? y/n

if the answer is not:
   The total gram of fat is ... and the calories are ...
   Would you like to start again? y/n
else
    
1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category:

Required submission:

  1. A short video.
  2. Copy and paste both programs.
  3. Submit the zipped project.

GUI: Dialog boxes

Classwork:
Write an OOD application, YI_WordValue.java to calculate the value of a word in the Scrabble game. Prompt the user for a word and display it worth using the table below:
Screen Shot 2015-02-11 at 12.19.37 PM

Write the tester class using a dialog box for user input.

Using dialog boxes
The JOptionPane class has the static showInputDialog method of t and supply the string that
prompts the input from the user.

Some examples:
String input = JOptionPane.showInputDialog(“Enter a word:”);
That method returns a String object.

You can also display output in a dialog box:
JOptionPane.showMessageDialog(null, “Word value: ” + worth);

Screen Shot 2015-02-18 at 11.10.45 AM

Any time you invoke the showInputDialog or showMessageDialog method in a program that
does not show any other frame windows, you need to add a line

System.exit(0);

to the end of your main method.

The showInputDialog method starts a user interface thread to handle user input. When the main method reaches the end, that thread is still running, and your program won’t exit automatically.

Calling the static method exit() from the System class, will force the program to exit. The parameter is the program’s status code. Zero represents a successful execution.


Screen Shot 2015-02-11 at 12.59.39 PM

Exit code is

0 when execution went fine;
1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.