Loading

[SOLVED] COMP 274 ENTIRE COURSE HELP

COMP274 entire course includes:

  • COMP 274 Week 1 Lab,
  • COMP 274 Week 2 Lab Inheritance and Polymorphism,
  • COMP 274 Week 3 Lab Java application GUI,
  • COMP 274 Week 4 Lab Java Program to Convert Temperature,
  • COMP 274 Week 5 Lab Timer and Mouse Events and Java Graphics,
  • COMP 274 Week 6 Lab Calendar Program,
  • COMP 274 Week 7 Lab Java Doc,

COMP 274 Week 1 Lab

Do the following two programs:

  1. Write a Java application that inputs three integers from the user and displays the sum, average, product, smallest and largest of the numbers. Use a Scanner object to get the input from the user. Use System.out to output the results. The average should be a floating point result, and should be displayed with 2 digits after the decimal point.
  2. Write a Java application which tests the random number generation abilities of Java. Random number generation is explained below.Your application should simulate rolling a pair of dice some number of times. Use a JOptionPane to ask the user how many times the dice should be rolled. Each dice roll can be a value between 1 and 6, so rolling 2 dice will result in values between 2 and 12. You need to generate a random number between 1 and 6 to simulate rolling each dice. Keep track of the result of each roll using an array that is indexed by the sum of the roll of the two dice. Output your result in a table which shows each value (ie. 2 – 12) and the number of times that value was rolled.

The program must have the following structure:

  1. The main function declares the counting array and gathers input from the user.
  2. A separate function is called which takes an integer array parameter as well as the number of dice rolls to execute. This function rolls the dice the required number of times and uses the array provided to count the number of times each value is rolled.
  3. The main program takes the count data from the array, formats it and displays it as described above.

For output, you should build a formatted string which includes tabs and new lines to represent your table. JOptionPanes by themselves are not capable of properly formatting tabs. However, there is another Java class which can be used with JOptionPanes to correctly display a formatted string. The JTextArea class understands all string formatting instructions. The following illustrates how to use the JTextArea class with a JOptionPane to display a formatted string.

#import javax.swing.JOptionPane;#import javax.swing.JTextArea;String output = “This \t is \t a \t formatted \t string. \n”;// Create a new JTextArea objectJTextArea area = newJTextArea( );// Place a formatted string into the JTextAreaarea.setText( output );// Place the text area into the JOptionPaneJOptionPane.showMessageDialog( null, area, “Title fordialog box”, JOptionPane.INFORMATION_MESSAGE );

For each of the two programming problems, create an Eclipse project and develop a Java program to solve the problem. Make sure to capture a sample of your program’s output. The best way to do this is to click on the console window you want to capture and then press the Alt and PrintScreen keys at the same time. Then paste your captured screen image into a Word document. For each of the two programs, put the screen capture followed by a copy of your source code into your Word document.
Random Numbers in Java
There are two different classes available to generate random numbers in Java. The static method random from the Math class can be used to generate a random floating point number from 0 up to but not including 1. This number can be scaled to whatever range of random numbers is desired.

(int)(Math.random( ) * 10);  //results in an integer between 0 and 9

The Random class from the java.util package can also be used to get random numbers. The nextInt method returns an integer from 0 up to but not including the argument value provided to the nextInt method.

Random rand = newRandom( );int number = rand.nextInt(10); //results in an integer between 0 and 9 minimumValue + differenceBetweenValues * rand.nextInt( scalingFactor )

The formula shown above is used to generate a range of random numbers starting at some minimum value and generating some specified number of random values. The scalingFactor determines how many different random values will be generated by the call to nextInt, starting with the value 0. The difference between values is usually 1.

Your final programming document should contain in the following order:

  1. Screen capture of the first program followed by source code.
  2. Screen capture of the second program followed by source code.
  3. Submit this as the Week 1 Programming Solution.

COMP 274 Week 2 Lab Inheritance and Polymorphism

The objective of this programming assignment is to experience the use of inheritance in Java and to see how polymorphism works with inheritance in Java.

The assignment involves writing three classes, plus a test class. The base class is an employee class which contains a couple of attributes common to all employees and a fundamental method to calculate pay. The two derived classes are a commissioned employee that adds payment of a sales commission as part of the pay calculation, and a union employee which adds overtime payment and union dues as part of the pay calculation. The test program will be structured to include a method which accepts a base class reference and demonstrates polymorphic behavior.

The details of the three classes to be implemented are as follows:

  • An Employee contains a name, a department where the employee works, and an hourly rate of pay. An explicit value constructor should be provided to set all three values when an Employee object is created. There should be mutator methods to set the values of the department and the pay rate. There should be one accessor method which returns a string containing the name and the department in which the employee works. Finally, there should be a weekly pay method that takes an integer parameter for the number of hours worked and returns the weekly pay. If the number of hours worked is less than 40 hours, the pay is the number of hours times the rate. If the number of hours worked is 40 or more, the pay is 40 times the rate.
  • The Union Employee inherits from the Employee class. A Union Employee contains a dues variable which holds the amount of dues a Union Employee has withheld from their paycheck each week. An explicit value constructor should be provided to set all three values from the base class along with the dues value. There should be a mutator method provided to set the dues variable. The base class weekly pay method should be overridden because a Union Employee gets 1.5 times the rate for any hours over 40 per week. This method should use the base class method to calculate pay for first 40 hours and then add the overtime amount. Also the weekly pay is reduced by the amount of dues withheld.
  • The Commission Employee inherits from the Employee class. A Commission Employee contains a commission rate and a sales amount variable which are used as part of the pay calculation. An explicit value constructor should be provided to set all 3 values of the base class along with the commission rate variable. There should be mutator methods for the commission rate and the sales amount. The base class weekly pay method should be overridden because the Commission Employee gets the base employee pay plus the commission rate times the sales amount. This method should use the base class weekly pay method to calculate the hourly part of the pay.
  • The test program needs to create a Union Employee object and a Commission Employee object. The test program must contain a display method which takes a base class Employee object reference along with the number of hours worked by the employee. The display method should use the base class method to get the employee name and department info and output that information. The display method should also use the base class method to get the weekly pay info for the employee object and display that information. The test program should pass the Union Employee object and the Commission Employee object to the display method along with the number of hours each employee has worked. It should test the payroll calculation for the number of hours worked to be less than 40, 40, and greater than 40 hours for each employee type. The output seen should demonstrate polymorphic behavior, that is the base class Employee reference to a Union Employee object elicits Union Employee pay calculations, and the base class Employee reference to a Commission Employee elicits Commission Employee payroll calculations.

Take screen shots of the output of the program. Paste the screen shots and your source code for all your classes into a Word document.

COMP 274 Week 3 Lab Java Application GUI

Create Java programs for the following two problems:

  1. Write a Java application to display the following GUI. At this point you are only implementing the display. We are not ready to make the calculator actually do any calculations! This program has the following requirements:
    1. The size of the calculator is 250 x 250 pixels.
    2. The background and foreground color of the calculator buttons must alternate in a checker board pattern as shown above. You can choose any pair of colors for your foreground and background colors.
    3. The buttons should have at least 5 pixels of space between them.
    4. The text on the buttons should be SanSerif size 16 and be bold.
    5. Your application should be implemented in a single class. The main method of the class does nothing more than create an object of the class. The constructor of the class creates and displays the GUI. The constructor may call other methods of the class if needed.
    6. The class must inherit from JFrame as the following demonstrates: publicmyGUI extendsJFrame { … }The extendskeyword specifies inheritance. Inside the classyou can directly access methods of the JFrame classwithout specifying an object due to inheritance. So when you want to add something to the frame, simply sayadd(someComponent);You can specify the title of the window in your constructor by simply adding the following line asthe first thing in your constructor.super(“Title of your window!”);
  2. Write a Java application to display the following GUI. At this point you are only implementing the display. This program has the following requirements:
    1. The textfield should accommodate 3 characters.
    2. The X and Y labels should be next to the corresponding textfields.

Hint:

  • Put each label and its adjacent text field into a panel, then put both panels into another panel.
  • The buttons should have 10 pixels horizontal spacing and 5 pixels vertical spacing.
  • For the layout of the JFrame, use FlowLayout( FlowLayout.CENTER, 10, 5).
  • Your application should be implemented in a single class. The main method of the class does nothing more than create an object of the class. The constructor of the class creates and displays the GUI. The constructor may call other methods of the class if needed.
  • Do not use inheritance for this program. Use a JFrame member variable as the main window object for this program.

Take screen shots of the output of programs 1 & 2. Paste the screen shots and your source code for your programs into a Word document.

Please place things in the following order:

  • Screen shot of problem 1.
  • Code for probem 1.
  • Screen shot of problem 2.
  • Code for problem 2.

COMP 274 Week 4 Lab Java Program to Convert Temperature

Write a Java GUI application to do temperature conversions between Celcius, Fahranheit, and Kelvin. The GUI display should look something like the following:

Your program must meet the following requirements:

  1. Do not use any of the GUI editing capabilities of Eclipse for this assignment. Do all the GUI layout work based on what you have learned in class in the last 2 weeks.
  2. The GUI and event handling setup should be done in the constructor of your GUI class or in private methods called from the constructor.
  3. The display must have a label and JTextField where the user inputs a value which must appear in the upper part of the frame as shown above.
  4. There should be a set of 3 radio buttons which indicate the input scale of the value to be converted. The 3 input scale buttons must be vertically aligned on the left side of the display as shown above.
  5. There should be a set of 3 radio buttons which indicate the output scale to be converted to. The 3 output scale buttons must be vertically aligned and appear on the right side of the display as shown above.
  6. Event handling must be setup so that selection of any input or output button causes an event which triggers the event handling code to determine which of 9 possible conversions is needed.
  7. Event handling must also respond to the user hitting the enter key in the input textfield! For this event, the event handling code must also determine which conversion is needed based on which buttons are selected.
  8. Display the conversion result in an output text field or in a JLabel which appears in the bottom part of the display as shown above. Output the degree symbol and output scale information as shown above. You can output a degree symbol by putting the character value 176 into a formatted string.
  9. If a radio button is clicked when there is nothing in the input textfield, the event handler must display the string “No Input” in the output textfield.
  10. Your program must accurately convert from Fahrenheit, Celcius, Kelvin to Fahrenheit, Celcius, Kelvin. Only the selected conversion is displayed in the output textfield.
  11. You must create a separate class which does all the temperature conversion calculations. It should have 6 static methods, one for each possible conversion. Each of the 6 methods takes an input temperature and returns the appropriate converted temperature. This class could be used in any other application where temperature conversion is needed. You can find conversion formulas at the following website:
    http://en.wikipedia.org/wiki/Temperature_conversion
  12. When the conversion selection changes due to clicking either an input or output scale button, the output area must change to show only the new result.

HINT:

  • For radio button events, use the ItemListener interface and use the isSelected method on the radio buttons to find out which buttons are turned on.
  • The output must display 2 digits after the decimal point.
  • Make sure that you test all your conversion formulas and the error case handling.
  • Also make sure that you add comments to your program.

Take screen shots of the program doing 2 different conversions and handling one of the error cases.

Paste the screen shots and the source code for your program into a Word document.

COMP 274 Week 5 Lab Timer and Mouse Events and Java Graphics

Introduction

The purpose of this week’s programming assignment is to learn how to deal with events from multiple sources. In addition, we will learn how to use some of Java’s graphics capabilities for drawing shapes in a display area. The programming assignment for this week is to implement a simple paddle ball game.

Paddle Ball Game Overview

The paddle ball game is a simplification of the Pong game. In the Pong game, a ball is moving around the display, bouncing off walls. The player moves a paddle in one dimension, trying to hit the ball whenever possible. If the ball hits the paddle, it bounces off and continues on its way. If the paddle misses the ball, the ball goes off the end of the display area and the player loses a point.

In our paddle ball game, the ball moves around the display, bouncing off walls just as in the Pong game. The player controls a paddle trying to hit the ball just like in the Pong game. If the ball hits the paddle, it bounces off and continues on its way. The main difference in our game is that if the player misses the ball, the ball simply bounces off the wall behind the paddle and continues to travel. There is no scoring in this game.

Object Oriented Design

If we analyze the game description we can see there are several different objects which are interacting. There is a ball object which is traveling around the display. There is a paddle object which is being moved by the player. There is a display which is presenting the graphical representation of the game to the user. These objects are readily apparent from the description of the game.

The ball object has a size and a position within the field of play. It also has a direction of travel in both the X and Y dimensions. The ball must be able to update its position when needed. Since the ball normally bounces off walls, it needs to know the length and width of the field of play when updating its position. The ball must also be able to draw itself.

The paddle has a size and a position within the field of play. The paddle must be able to update its position within the field of play. The paddle must also be able to draw itself.

The display has a display area which has a length and width. It has a means for drawing graphical shapes within the display area. The display area must be able to update the display area the position of the ball or paddle changes. The display itself has no concept of the game or its objects, so it will need to interact with some other object to draw all the game objects.

At this point, we have a ball, a paddle, and a display object. What is missing is some object which provides the game context. The ball has no awareness of the paddle. The paddle has no awareness of the ball. The display has no awareness of either the ball or paddle. We need an object which enforces the rules and concepts of the game and manages the behaviors of the other objects involved in the game.

Let’s call this the controller object. The controller has a ball, a paddle, and a display object. The controller manages game events. It gets mouse events and tells the paddle to update its position based on the position of the mouse cursor. It gets timer events and tells the ball to update its position based on the size of the display area which it gets from the display. It tells the display when to redraw the display area. It also provides a method which the display object uses to request the controller to draw the current state of the game. The controller is responsible for telling the ball and paddle to draw themselves.

The controller is also responsible for detecting when game objects are interacting. Specifically, it must be able to determine when the ball has made contact with the paddle. This requires that the controller is able to determine if a specific surface of the ball is in contact with a specific surface of the paddle. When this is detected, the controller tells the ball to reverse the direction of travel in the X or Y direction. This places a requirement on the ball and paddle to provide methods allowing the controller to determine the X or Y position of any given surface of the ball or paddle.

The Ball Class

Given that the ball has a size, a position, and moves a specific amount on each update, the Ball class will need member variables for all of these attributes. The size of the ball (diameter) and the number of pixels to move per update should be established when a ball object is created (explicit value constructor). To simplify things, the distance to move (increment) will initially be the same in the X and Y directions. The X and Y position members need to be set to some starting position by the constructor. The X, Y position of the ball is the upper left corner of the minimal box which contains the ball.

When the X increment is positive, the ball is traveling to the right. When it is negative it is traveling to the left. When the Y increment is positive the ball is traveling down. When it is negative it is traveling up.

According to the description in the previous section, the ball must provide the position of its edges to the controller. To do that, the Ball class provides the following methods:

  • getTop
  • getBottom
  • getLeft
  • getRight

The first two methods return the Y coordinate of the top/bottom edge of the ball. The other two methods return the X coordinate of the left/right edge of the ball. These values can easily be calculated from the X, Y position and the diameter of the ball. The Ball class must provide a method which takes a Graphics object parameter and uses it to draw the ball at its current position.

When the controller detects that the ball has hit the paddle, the controller must tell the ball to reverse its direction of travel in either the X or Y direction. To be flexible, the Ball class should provide two methods, one to reverse the X direction and one to reverse the Y direction. To the ball, reversing direction simply means negating the value of the X or Y increment.

The controller also must know whether the center of the ball is within the boundaries of the paddle in order to detect contact. This means the Ball class must provide methods to report its horizontal or vertical center. This can be easily computed from the current position and the diameter.

Finally, the Ball class provides a method which the controller calls any time the ball needs to change position. This method adds the X increment to the current X position, and the Y increment to the current Y position. The Ball class is responsible for detecting when it has encountered a wall. So, this method needs to know where the edges of the game area are. This method must be given the length and height of the game area as parameters. The following conditions must be checked for detecting contact with a wall:

  1. Top edge of ball <= 0 then reverse Y travel direction
  2. Bottom edge of ball >= height then reverse Y travel direction
  3. Left edge of ball <= 0 then reverse X travel direction
  4. Right edge of ball >= length then reverse X travel direction

The Paddle Class

The Paddle class has a length and a position. Both of these should be initialized by an explicit value constructor. That allows the controller to determine the paddle length and the position of the paddle relative to the wall. We will simplify things by stating that the paddle will have a horizontal orientation and will move left to right only. The paddle cannot move in the vertical direction once it has been created. The X and Y position of the paddle should represent the center of the top surface of the paddle. This will support the correlation of the mouse cursor position to the center of the paddle.

The draw method of the Paddle class takes a Graphics object parameter and draws a filled rectangle based on the current position of the paddle. Drawing a rectangle is based on the upper left corner of the rectangle as its reference position. Calculation of the reference position is easily done using the X and Y position of the paddle and the length of the paddle. The Paddle class controls what the width of the paddle will be.

To support the controller, the Paddle class must have methods which return the position of the top, bottom, left, and right edges of the paddle. The controller needs this information for detecting when the ball and paddle come into contact. The getTop and getBottom methods return a Y position. The getLeft and getRight methods return an X position. These values are easily calculated from the X and Y postion, and the length and width of the paddle.

Finally, a method must be provided to allow the controller to change the position of the paddle based on the X and Y coordinates of the mouse cursor. This method must restrict the movement of the paddle to changes to the X coordinate only.

The Display Class

The Display class provides a window to present the visual rendering of the state of the game. It also must interact with the controller. The easiest way to create a Display class which can draw various graphics is to have the class extend the JPanel class and override the paintComponent method. This method should simply fill a rectangle with some background color. The size of the rectangle is simply the size of the panel which is acquired from the getWidth and getHeight methods of the JPanel class. After drawing the background, the display object must pass its Graphics object to the controller, enabling the controller to arrange for the other game components to draw themselves.

The only other method needed in this class is an explicit value constructor which takes a controller object and stores it into a member variable. The constructor also creates a JFrame object storing it into a member variable. The display object adds itself to the JFrame. The frame initialization should be completed, including setting the initial size of the window which will display the game.

The Controller Class

The controller manages all aspects of the game including various game parameters. It determines the diameter of the ball and the distance the ball travels with each move. The distance travelled should be less than the diameter. The speed of ball movement is controlled by a combination of distance travelled and frequency of timer events. Timer events should be set up to occur around every 25 milliseconds. The length of the paddle should be at least twice the diameter of the ball. The game is to be set up so the paddle moves horizontally near the top of the display area. There should be at least 5% of the display height between the paddle and the top of the display area.

The Controller class contains a ball object, a paddle object, and a display object. In addition, the controller is responsible for managing the events that drive the game. Therefore, this class must implement the ActionListener interface to deal with Timer events which drive the ball. It must also implement the MouseMotionListener interface to cause the paddle to move based on mouse movement.

The constructor of this class creates the three objects mentioned above. It also must create a Timer object which will fire every 25 milliseconds and send ActionEvents to the controller object’s actionPerformed method. The last thing the constructor needs to do is to register the controller object as a mouseMotionListener on the display object. So, when the mouse cursor moves across the display area, MouseEvents will be delivered to the mouseDragged or mouseMoved methods of the controller object.

The controller provides a draw method which takes a Graphics object parameter and is called by the display object. This method should check to see if the ball and paddle objects exist, and if they do, ask each object to draw itself, passing the Graphics object into the draw methods of those objects.

The mouseDragged and mouseMoved methods are responsible for managing the padddle position. When a MouseEvent occurs and one of these methods executes, the method uses its MouseEvent parameter to get the current X and Y coordinates of the mouse cursor. These coordinates are given to the update method of the paddle which adjusts the paddle position based on these new coordinates. Once the paddle has been updated, the controller calls the repaint method on the display object to cause the display to reflect the new position of the paddle.

The controller’s actionPerformed method is responsible for causing the ball to move and detecting whether the ball is in contact with the paddle. It calls the update method on the ball, passing in the width and height of the display which it gets from the display object.

To detect whether the ball has just contacted the paddle, the following steps should be executed:

  1. Get the Y coordinates of the top of the ball and the bottom of the paddle.
  2. For contact to have just occurred, the top of the ball must be less than or equal to the bottom of the paddle, and it must also be greater than or equal to the bottom of the paddle minus the amount the ball just moved.
  3. If step 2 is true, the horizontal center of the ball must be between the left and right ends of the paddle.
  4. If step 3 is true, tell the ball to reverse its vertical direction.

Finally, the actionPerformed method invokes the repaint method to draw the display with the new position of the ball.

Play the Game

Create a test application that creates a controller object and play the game! Experiment with changing the game parameters and observe how the game reacts. When the game works, take a screen shot of the game. Turn in ALL your code along with the screen shot. Make sure that your code is fully commented.

COMP 274 Week 6 Lab Calendar Program

The Calendar Program

The purpose of this lab is to give you a chance to use some of the data stream tools we have been discussing in a simple application. The assignment is to write a calendar application which allows the user to select a date, and either retrieve a previously stored calendar entry, or save a calendar entry.

Your program should present a GUI interface which allows the user to specify the month, day, and year of the calendar entry. The GUI should also have a text area for displaying and editing a particular entry. It will also need two buttons, one for saving an entry, and the other for retrieving an entry.

Required program elements:

  • Your user interface must allow the user to enter the month, day, and year. You can do this using text fields for input, or you can use ComboBoxes if you feel adventurous.
  • The only GUI components which create events that your program needs to handle are the save and retrieve buttons.
  • You must have a separate class which manages the calendar data. You will have a minimum of three classes in your application, a user interface class, the calendar manager class, and a calendar test class. The user interface class creates an instance of the calendar manager in its constructor and stores it in a member variable.
  • The calendar manager must provide methods which support saving a specific calendar entry and retrieving a specific calendar entry. The interfaces must be defined to only pass a single day’s calendar entry across the interface.
  • The calendar manager must store calendar data into files according to month+year. That is, the calendar entries for December 2011 must all be stored in the same file.
  • The calendar manager must use ObjectInput/OutputStreams to read/write data from/to files. The calendar manager will use an array to store String objects. The position of a String in this array corresponds to the calendar entry for a specific day.
  • The save method of the calendar manager will need to determine if a file exists for the requested month and year. If so, the object from that file must be read into the calendar manager. Otherwise, the calendar manager must create an empty String array. The new entry must be saved to the appropriate day’s location in the array. The modified array must be saved to the appropriate file.
  • The retrieve method of the calendar manager will need to determine if a file exists for the requested month and year. If not, return an error string indicating that there is no such entry. If the file exists, read the String array from the file and locate the requested day’s entry. If this entry is null, return an error string indicating that there is no such entry, otherwise return the entry.

Take screen shots of the output of your program. Paste the screen shots and your source code for your programs into a Word document. Submit your Word document.

COMP 274 Week 7 Lab Java Doc

Documentation

The objective of this part of the lab is to create documentation using Javadoc for the Paddle Ball Game project from week 5. The following documentation requirements must be met:

  1. All commentary must use standard JavaDoc comments and tags.
  2. For every class add a class level comment including the author and the purpose of the class.
  3. Where one class heavily depends on the use of an object from another class, provide a link to the other class using the @see tag.
  4. For every method, add a method level comment which includes information on the purpose of the method, the method parameters, and the result returned by the method.
  5. Use the javadoc command to generate HTML files for your project.
  6. Use the browser to view your generated documentation to verify that all the required information for all the classes is included.

Consult the document provided describing how to export JavaDoc comments from Eclipse.

When your documentation is complete, turn in one of the following depending on what your instructor requires:

  1. Print outs of all the documentation pages from the browser.
  2. A Zip file containing all the documentation pages.

Deployment

Create a JAR file for the Paddle Ball Game project from week 5. The JAR file must contain all the class files needed to make the Paddle Ball Game work. Consult the document provided describing how to export a JAR file from Eclipse. To test if you have made your JAR file correctly, double click on your JAR file using Windows Explorer. The Paddle Ball Game should start running. If you are on Citrix, you will need to copy your game to a local computer before you can successfully execute it.

When you have successfully executed your JAR file, turn in a copy of your JAR file to your instructor.

Support