CSCI 2600 Homework 0: Setup and Java Introduction solution

$35.00

Original Work ?
Category: You will Instantly receive a download link for .ZIP solution file upon Payment

Description

5/5 - (1 vote)

If you would like to get more practice with Java, then we recommend walking through Oracle’s Java tutorials described under Problem 4. Try to complete Homework 0 first so you can use the tools we describe here when doing the examples in Oracle’s tutorial.

You are free to get help from anyone, on any portion of this problem set; that is, the academic integrity policy does not apply to this homework.

If you are having trouble with this assignment, get in touch with us immediately so we can try to get you back on track.

Getting Started

You must have Eclipse and Subclipse properly installed and must have checked out project csci2600 with package hw0 through SVN.

Throughout the course you will receive starter code and submit your assignments through Subversion (SVN). SVN is a version control system that allows software engineers to backup, manage, and collaborate on large software projects (you will learn more about SVN throughout the course).

Follow the instructions in the Verision Control handout, which outlines the basics of SVN.

Problem 1: Your first Java class—RandomHello

Create your Java class with a main method that will randomly choose, and then print to the console, one of five possible greetings that you define.

Create the file RandomHello.java, which will define a Java class named RandomHello that will reside in the Java package hw0; that is, assuming your project csci2600, its file name would be YourWorkspaceDirectory/csci2600/src/hw0/RandomHello.java.

Java requires every runnable class to contain a main method whose signature is public static void main(String[] args) (for example, the main methods in HelloWorld).

A code skeleton for the RandomHello class is shown below. Eclipse will generate some of this skeleton for you when you create the new RandomHello class.

RandomHello.java:

package hw0;
/**
 * RandomHello selects a random greeting to display to the user.
 */
public class RandomHello {
    /**
     * Uses a RandomHello object to print
     * a random greeting to the console.
     */
    public static void main(String[] argv) {
        RandomHello randomHello = new RandomHello();
        System.out.println(randomHello.getGreeting());
    }
    /**
     * @return a random greeting from a list of five different greetings.
     */
    public String getGreeting() {
        // YOUR CODE GOES HERE
    }
}

This skeleton is meant only to serve as a starting point; you are free to organize it as you see fit.

No Need to Reinvent the Wheel

Don’t write your own random number generator to decide which greeting to select. Instead, take advantage of Java’s Random class. (This is a good example of the adage “Know and Use the Libraries” as described in Chapter 7 of Joshua Bloch’s Effective Java. Learning the libraries will take some time, but it’s worth it!)

Type the following into the body of your getGreeting() method:

Random randomGenerator = new Random();

This line creates a random number generator. (Not a random number, which comes later, but a Java object that can generate random numbers. In Eclipse, your code may be marked as an error by a red underline. This is because the Random class is defined in a package that has not yet been imported (java.lang and hw0 are the only packages that are implicitly imported). Java libraries are organized as packages and you can only access Java classes in packages that are imported. To import java.util.Random, add the following line under the line package hw0; at the top of your file (after the package hw0; declaration):

import java.util.Random;

This will import the class Random into your file. To automatically add all necessary imports and remove unused imports, Eclipse lets you type CTRL-SHIFT-O to Organize your imports. Because there is only one class named Random, Eclipse will figure out that you mean to import java.util.Random and will add the above line of code automatically. (If the name of the class that needs to be imported is ambiguous — for example, there is a java.util.List as well as a java.awt.List — then Eclipse will prompt you to choose the one to import.)

Using java.util.Random

Read the documentation for Random‘s nextInt(int n) method by going to the Java API and selecting Random from the list of classes in the left-hand frame. Many classes also allow you to pull up documentation directly in Eclipse. Just hover over the class or method name and press SHIFT+F2.

Use the nextInt(int n) method to choose your greeting. You don’t have to understand all the details of its behavior specification, only that it returns a random number from 0 to n-1.

One way to choose a random greeting is using an array. This approach might look something like:

String[] greetings = new String[5];
greetings[0] = "Hello World";
greetings[1] = "Hola Mundo";
greetings[2] = "Bonjour Monde";
greetings[3] = "Hallo Welt";
greetings[4] = "Ciao Mondo";

The main method in the skeleton code above prints the value returned by getGreeting. So if you insert code in getGreeting to select a greeting randomly, when the class is run it will will print that greeting.

When you are finished writing your code and it compiles, run it several times to ensure that all five greetings can be displayed.

Again, now it would be a good idea to add and commit your new class to SVN .

Problem 2: Testing Java Code with JUnit

Part of your job as a software engineer is to verify that the software you produce works according to its specification. One form of verification is testing. JUnit is a framework for creating unit tests in Java. A unit test is a test for verifying that a given method in a class conforms to its specification. In this problem, we will provide you with a quick overview and simple example of how JUnit works. (Later homeworks will look more deeply into unit testing.)

Open both ../hw0/Fibonacci.java and ../hw0/test/FibonacciTest.java. From the comments, you can see that FibonacciTest is a test of the Fibonacci class.

Now run the JUnit test FibonacciTest.

A window or panel with a menacing red bar will appear, indicating that some of the tests in FibonacciTest did not complete successfully (see screenshot at right). The top pane displays the list of tests that failed, while the bottom pane shows the Failure Trace for the highlighted test. The first line in the Failure Trace should display an error message that explains why the test failed (it is the responsibility of the author of the test code to produce this error message).

If you click on the failure testThrowsIllegalArgumentException(), the bottom pane will switch to the appropriate error message. In this example, the first line of the failure trace shows that Fibonacci.java improperly threw an IllegalArgumentException when tested with zero (0) as its argument. (You may have to scroll the pane to the right to see this). If you double-click on the name of a test in the top pane, Eclipse will jump to the line where the failure occurred in the editor pane. Figure out the problem in Fibonacci.java, fix it, and rerun the JUnit test. Eclipse will automatically rebuild when you make changes, but if you are running Junit from the command line, you must manually rebuild (compile) Fibonacci.java before you rerun JUnit. In Eclipse, this can be done by following the compiling instructions and then clicking the “Run” button.

Use the information in the Failure Trace box to help you continue debugging Fibonacci. Keep a record of what you did to debug Fibonacci as you will have to answer questions about your debugging experience in the next problem. After you have fixed all the problems in Fibonacci, you should see a bright green bar instead of a red one when you run FibonacciTest.

Problem 3: Answering Questions About the Code

In a newly created text file, answer some questions about the Fibonacci class. Most programming homeworks that you will be assigned will require you to submit some sort of response or write-up in addition to your code. Follow these instructions to create a text file, named hw0/answers/problem3.txt, with answers to the following questions:

  1. Why did Fibonacci fail the testThrowsIllegalArgumentException test? What did you have to do to fix it?
  2. Why did Fibonacci fail the testBaseCase test? What (if anything) did you have to do to fix it?
  3. Why did Fibonacci fail the testInductiveCase test? What (if anything) did you have to do to fix it?

Problem 4: Getting a Real Taste of Java—Balls and Boxes

Until now, we have only been introducing tools. In this problem, we will delve into a real programming exercise. If you are not familiar with Java, we recommend working through the Oracle’s Learning the Java Language tutorial. (Skip the section on generics for now.) Fragments of Oracle’s other tutorials may also be useful, specifically “Getting Started”, “Essential Java Classes”, and “Collections”.

This problem is intended to give you a better sense of what Java programming entails. This problem can be somewhat challenging. Don’t be discouraged, we’re here to help. And we expect that time spent now will pay off significantly during the rest of the course.

As you work on this problem, record your answers to the various questions in problem4.txt in the project’s hw0/answers/ directory.

  1. Warm-Up: Creating a Ball:

    Take a look at ../hw0/Ball.java. A Ball is a simple object that has a volume.

    • What is wrong with Ball.java? Please fix the problems with Ball.java and document your work in problem4.txt.

    We have included a JUnit test called ../hw0/test/BallTest.java to help you out. In Eclipse, one of its warnings should help you find at least one of the bugs without referring to the JUnit results.

  2. Using Pre-Defined Data Structures:

    Next, we want to create a class called BallContainer. As before, skeleton code is provided (see BallContainer.java). A BallContainer is a container for Balls. BallContainer must support the following methods and your task is to fill in the code that will implement all these methods correctly:

    • add(Ball)
    • remove(Ball)
    • getVolume()
    • size()
    • clear()
    • contains(Ball)

    The specifications for these methods are found in the code BallContainer.java.

    In BallContainer, we use a java.util.Set to keep track of the balls. This is a great example of using a predefined Java data-structure to save yourself significant work.

    Before implementing each method, read the documentation for Set. Some of your methods will be as simple as calling the appropriate predefined methods for Set. To help you out, we have included a JUnit test called ../hw0/test/BallContainerTest.java.

    Before you start coding, please take time to think about the following question (which you need to answer in the text file):

    There are two obvious approaches for implementing getVolume():

    • Every time getVolume() is called, go through all the Balls in the Set and add up the volumes. (Hint: one solution might use a for-each loop to extract Balls from the Set.)

    • Keep track of the total volume of the Balls in BallContainer whenever Balls are added and removed. This eliminates the need to perform any computations when getVolume is called.

    Which approach do you think is the better one? Why?

  3. Implementing a Box:

    In this problem, you will do a little more design and thinking and a little less coding. You will implement the Box class. A Box is also a container for Balls. The key difference between a Box and a BallContainer is that a Box has only finite volume. Once a box is full, we cannot put in more Balls. The size (volume) of a Box is defined when the constructor is called:

    public Box(double volume);

    Since a Box is in many ways similar to a BallContainer, we internally keep track of many things in the Box with a BallContainer, allowing us to reuse code. Many of the methods in Box can simply “delegate” to the equivalent in BallContainer; for example, removing from a Box cannot cause it to exceed its volume limit. This design of having one class contain an object of another class and reusing many of the latter class’s methods is called composition.

    (Optional Note: If you are familiar with Java, you may wonder why we did not simply make Box extend BallContainer via “inheritance”; that is, why did we not make Box a subclass of BallContainer. We will discuss this much more deeply later in the course, but the key idea is that Box is not what we call a true subtype of BoxContainer because it is in fact more limited than BallContainer (a Box can only hold a limited amount); hence, a user who uses a BallContainer in his code can not simply substitute that BallContainer with a Box and assume the same behavior in his program. (The code may cause the Box to fill up, but he did not have this concern when using a BallContainer). For this reason, it is not a good idea to make Box extend BallContainer.)

    In addition to the constructor described above, you will need to implement the following new methods in Box:

    • add(Ball)
    • getBallsFromSmallest()

    The specifications for these methods can be found in the code Box.

    A few things to consider before you start writing code:

    • You shouldn’t need to implement your own sorting algorithm. Instead, take advantage of the Java API (remember: “Know and Use the Libraries”).
    • Also, you shouldn’t need to change your implementation of BallContainer or Ball for this problem. In particular, you should not implement the Comparable interface. If you are tempted to do so, consider using Comparator instead. Comparator is a companion interface to Comparable and is used throughout the Java libraries: check out the sort methods in java.util.Collections as an example.
    • If you do make any changes to BallContainer or Ball for this problem, then explicitly document what changes you made and why in problem4.txt.
    • Be cautious if you plan on using Java’s TreeSet; remember that TreeSet does not store duplicates, and if you provide a TreeSet with a Comparator, it will use that Comparator to determine duplication. See the TreeSet API documentation for more details.
    • Before you start working on getBallsFromSmallest(), we recommend strongly that you consider using Iterator.
    • The JUnit test ../hw0/test/BoxTest.java should help you out. However, we do not guarantee that the tests we provide will catch all bugs in your program.
    • Oh yeah, don’t forget to commit your code more than occasionally.

    Also, take some time to answer the following questions in your text file:

    • There are many ways to implement getBallsFromSmallest(). Briefly describe at least two different ways. Your answers should differ in the implementation of Box, not in lower-level implementation (for example, using an insertion sort instead of a selection sort is a lower-level implementation because it does not affect how Box is implemented). Hint: think about different places in the Box class where you could add code to achieve the desired functionality.
    • Which of the above ways do you think is the best? Why?

    There is no one correct answer. Our intent is to help you fight that urge to code up the first thing that comes to mind. Remember: More thinking, less coding.

Problem 5: Turning In Your Homework

You will turn in the solutions for the problem sets, including this one, by checking them into your SVN repository. All the relevant files should be included, for example:

  • Java source files we provide that you change.
  • Java source code you write.
  • Text files, drawings, or documentation of your code.

Each homework will indicate exactly what you need to turn in a Section entitled “What to Turn In”.

In Eclipse, usually all you’ll need to do is right-click on the hw0 folder in Package Explorer, then select Team » Commit. You don’t need to worry about files you have added (e.g., RandomHello.javaproblem3.txt). Eclipse will automatically ask you if you want to include these files in the commit.

After completing the above steps, all your code and materials to turn in should be in your SVN repository. Proceed to the Homework Server to complete the submition of the assignment!

Very Important! You must click the Grade SVN button for your homework to be submitted for grading. Committing the files is not enough. If you don’t click the Grade SVN button to submit the files, your homework will not be graded.

IMPORTANT: Make sure that you have the correct directory structure. If you break the structure, compilation on the Homework Server will fail resulting in a grade of 0. At this point, you must have project csci2600 with subdirectory src. Directory src must have subdirectory hw0 and hw0 must have subdirectories answersdocs and test. These show as hw0hw0.answershw0.docs and hw0.test subfolders of src in Project Explorer. The Java classes (e.g., Ball.java) must be in hw0, your text files (problem3.txt and problem4.txt) must be in answers and the JUnit test classes (e.g., BallTest.java) must be in test.

What to Turn In

We should be able to find the following directories and files in your src directory:

  • hw0/RandomHello.java that prints out one of five random messages when its main method is executed.
  • hw0/Fibonacci.java that passes the three tests in hw0/test/FibonacciTest.java. (Note that you should NOT edit hw0/test/FibonacciTest.java to accomplish this task.)
  • hw0/Ball.javahw0/BallContainer.java and hw0/Box.java that pass their respective JUnit tests. (Again, you should not modify the JUnit tests, though you are most welcome to read the source code to understand what they test for).
  • hw0/answers/problem3.txt and hw0/answers/problem4.txt containing answers to the questions in Problems 3 and 4.

Grade Breakdown

This homework is worth 50 points. The Homework Server runs the provided JUnit tests (plus a few additional tests). Test and debug your code in Eclipse before before committing and submitting on the Homework Server! If your code passes the tests in Eclipse, then it should pass them on the Homework Server too.

  • Compilation: 4pts (auto-graded)
  • FibonacciTest JUnit tests: 4pts (each test 1pt, auto-graded)
  • BallTest: 1pt (auto-graded)
  • BallContainerTest: 8pts (auto-graded)
  • BoxTest: 16pts (each test 2pts, auto-graded)
  • Instructor Box tests: 4pts (auto-graded)
  • Answers to Problem 3 questions: 3pts
  • Answers to Problem 4 questions: 10pts

Parts of this homework are copied from University of Wanshington’s Software Design and Implementation course