当前位置:天才代写 > JAVA代写,java代考-JAVA作业代写免费Moss检测 > java lab代写 CS代写(C)CPS 209 Labs, Spring 2018

java lab代写 CS代写(C)CPS 209 Labs, Spring 2018

2018-11-23 08:00 星期五 所属: JAVA代写,java代考-JAVA作业代写免费Moss检测 浏览:1071

java lab代写 There are ten labs total in the course (C)CPS 209 Computer Science II taught by Ilkka Kokkarinen during the Spring 2018 term.

(C)CPS 209 Labs, Spring 2018

There are ten labs total in the course (C)CPS 209 Computer Science II taught by Ilkka Kokkarinen during the Spring 2018 term. The same ten labs are used in the daytime science transition program and in the Ryerson Chang School of Continuing Education.

 Since many of these labs refer to the work done in the previous labs, you should create one BlueJ project folder named “209 Labs” into which you write all these ten labs. In this same project folder, you should also add the JUnit test classes provided by the instructor, and the text file warandpeace.txt of the classic novel known for its extreme length that is used as a “big data” (well, big enough for the era that it comes from) source for some of the JUnit tests for the labs. You should download and save this text file inside this project folder from the DropBox link. Do not edit this text file in any way, not even to just add or remove some little whitespace character.

 

Each of these ten labs is worth the same two points of your total course grade. For labs 5, 7 and 9 that ask you to write a Swing component, these two marks are given for these components passing the visual inspection of the behaviour specified in the lab. The other seven labs must cleanly pass the JUnit tester of that week to receive the two points for that lab. No partial marks whatsoever are given for labs that do not not pass these tests. In all computation, being 99% correct is same as being 0% correct. (And in fact, in many situations the former would be much worse.)

 

To compensate for this strict policy of correctness and to simplify the job for handling the labs in this double-paced course, in both daytime science transition course and evening Chang School course, all ten labs have the exact same deadline, the noon the day after the last lecture. Before that, there is no rush to complete any lab, so you can take your time to get each lab to work so that it will pass the JUnit tests. You can then simply come to each lab session to work on and get help for whichever lab you are currently working on.

 

In all these labs, silence is golden. Since many of these JUnit testers will test your code with a large number of pseudo-randomly generated test cases, your methods should be absolutely silent and print nothing on the console during their execution. Any lab that prints anything at all on the console during the execution will be unconditionally rejected and receive a zero mark.

 

You may not modify the JUnit testers provided by the instructor in any way whatsoever, but your classes must pass these tests exactly the way that your instructor wrote them. Modifying a JUnit tester to make it seem that your class passes that test, even though it really does not, is considered serious academic dishonesty and will be automatically penalized by the forfeiture of all lab marks in the course.

 

Once you have completed all the labs that you think you are going to complete before deadline, you will submit all your completed labs in one swoop as the entire “209 Labs” BlueJ project folder that contains all the source files and the provided JUnit testers. Even if you write your labs working on Eclipse or some other IDE, it is compulsory to submit these ten labs as one BlueJ project folder. No other form of submission is acceptable.

 

The students in Chang School should submit their completed project folders as email attachments to ilkka.kokkarinen@gmail.com. The students in the daytime transition program course will have the course TA set up a system for lab submissions, and they should not send their labs to the instructor.

 

ACCIDENTS HAPPEN, SO MAKE FREQUENT BACKUPS OF THE LAB WORK THAT YOU HAVE COMPLETED. SERIOUSLY. THIS CANNOT BE EMPHASIZED ENOUGH IN NOT JUST THIS COURSE, BUT IN ALL OUR LIVES IN THIS AGE OF COMPUTERS.

 

Lab 1

JUnit: PolynomialTestOne.java

 

In spirit of the Fraction example class seen in the first lecture, your first task in this course is to implement the class Polynomial whose objects represent polynomials of variable x with integer coefficients, and their basic mathematical operations. (If your math skills on polynomials have become a bit rusty since you last used them back in high school, check out the page Polynomials in the “College Algebra” section of “Paul’s Online Math Notes“, the best and still very concise online resource for college level algebra and calculus that I know of.) As is good programming style unless there exist good reasons to do otherwise, this class will be intentionally designed to be immutable so that Polynomial objects cannot change their internal state after they have been constructed. The public interface of Polynomial should consist of the following instance methods.

 

@Override public String toString()

 

Implement this method first to return some kind meaningful, human readable String representation of this instance of Polynomial. This method is not subject to testing by the JUnit testers, so you can freely choose for yourself the textual representation that you want this method to produce. Having this method implemented properly will become immensely useful for debugging the remaining methods that you will write inside Polynomial class.

 

public Polynomial(int[] coefficients)

 

The constructor that receives as argument the array of coefficients that define the polynomial. For a polynomial of degree n, the array coefficients contains exactly n + 1 elements so that the coefficient of the term of order k is in the element coefficients[k]. For example, the polynomial

 

5x3 – 7x + 42 that will be used as example in all of the following methods would be given as the coefficient array {42, -7, 0, 5}.

 

Terms missing from inside the polynomial are represented by having a zero coefficient in that position. However, the coefficient of the highest term of every polynomial should always be nonzero, unless the polynomial itself is identically zero. If this constructor is given as argument a coefficient array whose highest terms are zeroes, it should simply ignore those zero terms. For example, if given the coefficient array {-1, 2, 0, 0, 0}, the resulting polynomial would have degree of only one, as if that argument array had really been {-1, 2} without these leading zeros.

 

To guarantee that the Polynomial class is immutable so that no outside code can ever change the internal state of an object after its construction (at least not without resorting to underhanded tricks such as reflection), the constructor should not assign only the reference to the coefficients array to the private field of coefficients, but it must create a separate but identical defensive copy of the argument array, and store that defensive copy instead. This ensures that the stored coefficients of the polynomial do not change if somebody later changes the contents of the shared coefficients array that was given as the constructor argument.

 

public int getDegree()

 

Returns the degree of this polynomial. For example, the previous polynomial has degree 3.

 

public int getCoefficient(int k)

 

Returns the coefficient for the term of order k. For example, the term of order 3 of the previous polynomial equals 5, and the term of order 0 equals 42.

 

public int evaluate(int x)

 

Evaluates the polynomial using the value x for the unknown symbolic variable of the polynomial. For example, when called with x = 2 for the previous example polynomial, this method would return 68. Your method does not have to worry about potential integer overflows, but can assume that the final and intermediate results of this computation will always stay within the range of int.

 

Lab 2

JUnit: PolynomialTestTwo.java

 

The second lab continues with the Polynomial class from the first lab by adding new methods for polynomial arithmetic in its source code. (There is no inheritance or polymorphism yet in this lab.) Since the class Polynomial is designed to be immutable, none of the following methods should

 

modify the objects this or other in any way, but return the result of that arithmetic operation as a brand new Polynomial object created inside that method.

 

public Polynomial add(Polynomial other)

 

Creates and returns a new Polynomial object that represents the result of polynomial addition of the two polynomials this and other. This method should not modify this or other polynomial in any way. Make sure that just like with the constructor, the coefficient of the highest term of the result is nonzero, so that adding the two polynomials 5x10 x2 + 3x and -5x10 + 7, each of them of degree 10, produces the result polynomial –x2 + 3x + 7 that has a degree of only 2 instead of 10.

 

public Polynomial multiply(Polynomial other)

 

Creates and returns a new Polynomial object that represents the result of polynomial multiplication of the two polynomials this and other. Polynomial multiplication works by multiplying all possible pairs of terms between the two polynomials and adding them together, combining the terms of equal rank together into the same term.

 

Lab 3

JUnit: AccessCountArrayListTest.java

 

In the third lab, you get to practice using class inheritance to create your own custom subclass versions of existing classes in Java with new functionality that did not exist in the original superclass. Your third task in this course is to use inheritance to create your own custom subclass AccessCountArrayList<E> that extends the good old ArrayList<E> from the Java Collection Framework. This subclass should keep an integer count of how many times the methods get and set have been called. (One counter keeps the simultaneous count for both methods.)

 

You should override the get and set methods so that both of them first increment the access count and then call the superclass version of that same method (use the prefix super in the method call to force this), returning whatever result the superclass version returned. In addition to these overridden methods inherited from the superclass, your class should define the following two brand new methods:

 

public int getAccessCount()

 

Returns the current count of how many times the get and set methods have been called for this

object.

 

public void resetCount()

 

Resets the access count field of this object back to zero.

 

Lab 4

JUnit: PolynomialTestThree.java

 

In this fourth lab, we continue modifying the source code for the Polynomial class from the first two labs to allow equality and ordering comparisons to take place between objects of that type. Modify the class definition so that this class now implements Comparable<Polynomial>. Then write the following methods to implement equality and ordering comparisons.

 

@Override public boolean equals(Object other)

 

Returns true if the other object is also a Polynomial of the exact same degree as this, so that the coefficients of this and other polynomial are pairwise equal. If the other object is anything else, this method returns false. (You can actually implement this method last after implementing the method compareTo, since at that point its logic will be a one-liner after the instanceof check.)

 

@Override public int hashCode()

 

Whenever you override the equals method in a subclass, you should also override the hashCode method to ensure that two objects that their equals method considers to be equal will also have equal hash codes. This method computes and returns the hash code of this polynomial, used to store and find this object inside some instance of HashSet<Polynomial>, or some other hash table based data structure. This hash code is computed by adding up the coefficients of this polynomial, but so that the coefficient for term k is multiplied by the element in position k % 5 in the array [547, 619, 877, 1013, 1163]. Define that array inside your class as a named constant MULTIPLIERS.

 

public int compareTo(Polynomial other)

 

Implements the ordering comparison between this and other polynomial, as required by the interface Comparable<Polynomial>, allowing the instances of Polynomial to be sorted or stored inside some instance of TreeSet<Polynomial>. This method returns +1 if this is greater than other, -1 if other is greater than this, and 0 if both polynomials are equal in the sense of the equals method.

 

A total ordering relation between polynomials is defined by the rule that any polynomial of higher degree is automatically greater than any polynomial of lower degree, regardless of their coefficients. For two polynomials whose degrees are equal, the result of the order comparison is determined by the highest-order term for which the coefficients of the polynomials differ, so that the polynomial with a larger such coefficient is considered to be greater in this ordering.

 

 

Be careful to ensure that this method ignores the leading zeros of high order terms if you have them inside your polynomial coefficient array, and that the ordering comparison criterion is precisely the one defined in the previous paragraph.

 

Lab 5

In this lab, your task is to create a custom Swing GUI component Head that extends JPanel. To practice working with Java graphics, this component displays a simple human head that, to also practice the Swing event handling mechanism, reacts to the mouse cursor entering and exiting the surface of that component. You should copy-paste a bunch of boilerplate code from the example class ShapePanel into this class. Your class should contain one field a private boolean mouseInside, and the following methods:

 

public Head()

 

The constructor of the class should first set the preferred size of this component to be 500 by 500 pixels, and then give this component a decorative raised bevel border using the utility method BorderFactory.createBevelBorder. Next, this constructor adds a MouseListener to this component, this event listener object constructed from an inner class MyMouseListener that extends MouseAdapter. Override both methods mouseEntered and mouseExited inside your event listener class to first set the value of the field mouseInside accordingly and then call repaint.

 

@Override public void paintComponent(Graphics g)

 

Renders some kind of image of a simple human head on the surface of this component. This is not an art course so this head does not need to look fancy, but a couple of simple rectangles and ellipses suffice. (Of course, interested students of more artistic bent might want to try out more complicated shapes from the package java.awt.geom to produce a more aesthetically pleasing image.) If the value of the field mouseInside is true, the eyes should be drawn to be open, whereas if mouseInside is false, the eyes should be drawn to be closed. (As long as the eyes are somehow noticeably visually different based on the mouse entering and exiting the component surface, that is enough for this lab.)

 

To admire your reactive Swing component on the screen, write a separate HeadMain class that contains a main method that creates a JFrame that contains four separate Head components arranged in a neat 2-by-2 grid using the GridLayout layout manager.

 

Lab 6

JUnit: WordCountTest.java

 

 

This lab lets you try out reading in text data from the given BufferedReader and performing computations on that data. To practice working in a proper object-oriented framework, we design an entire class hierarchy that reads in text one line at the time and performs some operation for each line. The subclasses can then decide what that operation is by overriding the template methods used by this algorithm.

 

To allow this processing to return a result of arbitrary type that can be freely chosen by the users of this class, the abstract superclass of this little framework is also defined to be generic. Start by creating the class public abstract class FileProcessor<R> that defines the following three abstract methods:

 

protected abstract void startFile();

protected abstract void processLine(String line); protected abstract R endFile();

 

and one concrete final method that is therefore guaranteed to be the same for all the future subclasses in this entire class hierarchy:

 

public final R processFile(BufferedReader in) throws IOException

 

This method should first call the method startFile. Next, it reads all the lines of text coming from in one line at the time in some kind of suitable loop, and calls the method processLine passing it as argument each line that it reads in. Once all incoming lines have been read and processed, this method should finish up by calling the method endFile, and return whatever the method endFile returned.

 

This abstract superclass defines a template for a class that performs some computation for a text file that is processed one line at the time, returning a result whose type R can be freely chosen by the concrete subclasses of this class. Different subclasses can now override the three template methods startFile, processLine and endFile methods in different ways to implement different computations on text files.

 

As the first application of this mini-framework (but it is a proper framework, since you now write methods for this framework to call, instead of the framework offering methods for you to call), you will emulate the core functionality of the Unix command line tool wc that counts how many characters, words and lines the given file contains. Those of you who have taken the Unix and C programming course CPS 393 should already recognize this handy little tool, but even if you have not taken that course, you can still implement this tool based on the following specification of its behaviour.

 

Create a class WordCount that extends FileProcessor<List<Integer>>. This class should contain three integer fields to keep track of these three counts, and the following methods:

 

 

protected void startFile()

 

Initializes the character, word and line counts to zero.

 

protected void processLine(String line)

 

Increments the character, word and line counts appropriately. In the given line, every character increments the count regardless whether it is a whitespace character or not. To count the words in the given line, count the non-whitespace characters that either begin that line, or whose previous character on that line is some whitespace character. You must use the utility method Character.isWhitespace to test whether some character is a whitespace character, since the Unicode standard defines quite a lot more whitespace characters than most people would expect.

 

protected List<Integer> endFile()

 

Creates and returns a new List<Integer> instance (choose the concrete subtype of this result object yourself) that contains exactly three elements; the character, word and line counts, in that order.

 

Lab 7

This seventh lab lets you create a Swing component that displays a real-time animation using Java concurrency to execute an animation thread that runs on its own independently of what the human user happens to be doing with the component. This thread will animate a classic particle field where a swarm of thousands of independent little particles buzzes randomly around the component. (This same architecture could then, with surprisingly little modification, be used to implement some real-time game, with this animation thread moving the game entities according to the rules of the game 50 frames per second, and the event listeners giving orders to the game entity that happens to represent the human player.)

 

First, create a class Particle whose instances represent individual particles that will randomly around the two-dimensional plane. Each particle should remember its x– and y-coordinates on the two-dimensional plane, stored in two data fields of type double. This class should also have a random number generator shared between all objects:

 

private static final Random rng = new Random();

 

The class should then have the following methods:

 

public Particle(int width, int height)

 

The constructor that places this particle in random coordinates inside the box whose possible values for the x-coordinate range from 0 to width, and for the y-coordinate from 0 to height.

 

public double getX() public double getY()

 

The accessor methods for the current x– and y-coordinates of this particle.

 

public void move()

 

Adds the value of the expression rng.nextGaussian() separately to the x– and y-coordinates of this particle, thus moving this particle a random distance to a random direction in the spirit of Brownian motion.

 

Having completed the class to represent individual particles, write a class ParticleField that extends javax.swing.JPanel. The instances of this class represent an entire field of random particles. This class should have the following private instance fields.

 

private boolean running = true;

private java.util.List<Particle> particles = new java.util.ArrayList<Particle>();

 

The class should have the following public methods:

 

public ParticleField(int n, int width, int height)

 

The constructor that first sets the preferred size of this component to be width-by-height. Next, creates n separate instances of Particle and places them in the particles list.

 

Having initialized the individual particles, this constructor should create and launch one new Thread using a Runnable argument whose method run consists of one while(running) loop. The body of this loop should first sleep for 20 milliseconds. After waking up from its sleep, it should loop through all the particles and call the method move() for each of them. Then call repaint() and go to the next round of the while-loop.

 

@Override public void paintComponent(Graphics g)

 

Renders this component by looping through particles and rendering each one of them as a 3-by-3 pixel rectangle to its current x– and y-coordinates.

 

public void terminate()

 

Sets the field running of this component to be false, causing the animation thread to terminate in the near future.

 

To admire the literal and metaphorical buzz produced by your particle swarm, write another class ParticleMain that contains a main method that creates one JFrame instance that contains a ParticleField of size 800-by-800 that contains 2,000 instances of Particle. Using the main method of the example class SpaceFiller as a model of how to do this, attach a WindowListener to the JFrame so that the listener’s method windowClosing first calls the method terminate of the ParticleField instance shown inside the JFrame before disposing that JFrame itself.

 

Lab 8

JUnit: TailTest.java

 

In this lab, we return to the FileProcessor<R> framework from Lab 6 for writing tools that process text files one line at the time. This time this framework is used to implement another Unix command line tool tail that can be used to extract the last n lines of the given file. Write a class Tail that extends FileProcessor<List<String>> and has the following methods:

 

public Tail(int n)

 

The constructor that stores its argument n, the number of last lines to return as the result, into a private data field. In this lab, you have to choose for yourself what instance fields you need to define in your class to make the required methods work.

 

@Override public void startFile()

 

Start processing a new file from the beginning. Nothing to do here, really.

 

@Override public void processLine(String line)

 

Process the current line. Do something intelligent here. Be especially careful not to be a “Shlemiel” so that your logic of processing each line has to loop through all of the previous lines that you have collected and stored so far. As a hint to avoid being a “Shlemiel”, note that the List<String> that you create and return does not necessarily have to be specifically an ArrayList<String>, but perhaps some other subtype of List<String> that allows O(1) mutator operations at both of its ends would be much more appropriate to use here.

 

@Override public List<String> endFile()

 

Returns a List<String> instance that contains precisely the n most recent lines that were given as arguments to the method processLine in the same order that they were originally read in. If fewer

 

than n lines have been given to the method processLine since the most recent call to the method

startFile, this list should contain as many lines as have been given.

 

Lab 9

In this lab you write one last graphical Swing component that displays a Lissajous curve on its surface, so that the user can control the parameters a, b and delta that define the shape of this curve by entering their values into three JTextField components inside this component. Write a class Lissajous that extends JPanel, and the following methods in it:

 

public Lissajous(int size)

 

The constructor that sets the preferred size of this component to be size-by-size pixels. Then, three instances of JTextField are created and added inside this component. Initialize these text fields with values 2, 3 and 0.5. Add an ActionListener to each of the three text fields whose method actionPerformed simply calls repaint for this component.

 

@Override public void paintComponent(Graphics g)

 

Renders the Lissajous curve on the component surface, using the values for a, b and delta that it reads from the previous three text fields. This method should consist of a for-loop whose loop counter double t goes through the values from 0 to (a + b) * Math.PI using some suitably small increment. In the body of the loop, compute the coordinates x and y of the current point using the formulas

 

x = size/2 + 2*size/5 * Math.sin(a * t + delta); y = size/2 + 2*size/5 * Math.cos(b * t);

 

and draw a line segment from the current point to the previous point.

 

Again, to get to admire your Lissajous curve and try out the effect of the values of a, b and delta on the shape of the curve as if you were inside the lair of a mad scientist in some 1970’s dystopian science fiction movie, create a separate class LissajousMain whose main method creates a JFrame that contains your Lissajous component. The end result might look like this:

 

""that produces the lines of this text file as a stream of strings, one line at the time. The method should then use filter to keep only those whose length is greater or equal to the threshold value thres, and in the end, return a count how many such lines the file contains.

 

public List<String> collectWords(Path path) throws IOException

 

This method should also use the same utility method Files.lines to first turn its parameter path into a Stream<String>. Each line should be converted to lowercase and broken down to individual words that are passed down the stream as separate String objects (the stream operation flatMap will be handy here). Split each line into its individual words using the separator regex “[^a-z]+” for the method split in String. In the next stages of the computation stream, discard all empty words, and sort the remaining words in alphabetical order. Multiple consecutive occurrences of the same word should then be removed (use the stream operation distinct, or if you want to do this yourself the hard way as an exercise, write a custom Predicate<String> subclass whose method test accepts its argument only if it was the first one or distinct from the previous argument), and to wrap up this computation stream, collected into a List<String> that is returned as the answer.

最先出自天才代写 java代写
合作:幽灵代写

 


 

 

天才代写-代写联系方式