Class Note for C SC 227 at UA
Popular in Course
Popular in Department
This 21 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at University of Arizona taught by a professor in Fall. Since its upload, it has received 12 views.
Reviews for Class Note for C SC 227 at UA
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 02/06/15
Chapter 4 Software Development Warning This chapter has not been edited yet It is also incomplete as Rick Considers how much ofthe Jukebox should be developed Chapter Goals 0 Find Objects 0 Introduce one way to develop software 0 Write tests at the same time as writing code This chapter introduces some techniques that help programmers develop high quality software that is easy to understand modify and maintain There are many software development processes that could be presented here For example the traditional waterfall approach suggests analysis and gathering of requirements guring out everything the system must do before all else Then the system is designed which requires a lot of documentation On large projects analysis and design can take months and even years before a single line of code gets written Discrete steps are imposed that require analysis to be completed before design design before coding and coding before testing This waterfall process also has some severe problems The development team has to be almost clairvoyant with little room for error Waterfall places the high risk and dif cult tasks toward the end of the project when it can be too late to debug them Craig Larrnan s book1 provides proof that waterfall has proved to be a terrible way to develop software In one study 87 of all projects failed The waterfall process was the quotsingle largest contributing factor for failure being cited in 81 of the failed projects as the number one problem quot He quotes a joke about a guy who fell off a cliff As he was hurtling down someone at the top ofthe ch yelled to the guy who isfalling quotHow are you doingquot The guy replied quotSofar so good 1 Agile and Iterative Development a Manager39s Guide AddisonWesley Professional 2003 76 Software Development Recently industry and academia have been adopting an agile approach to software development implying less emphasis on documentation Agile processes still have analysis design coding testing and documentation however these methods emphasize working software as the primary measure of progress Software developers work with customersithose wanting the softwarei in order to prioritize what is most important Developers code and test to get those features Design is employed but throughout the whole process Testing is done but it is done all along Some agile practices will now be demonstrated in the context of building a software system This narrative describes what the system should be able to do The student affairs office has decided to put some newfound activity fee funds toward a music jukebox in the student center The jukebox will allow a student to play individual songs No money will be required Instead a student will swipe a magnetic ID card through a card reader Students will each be allowed to play up to 2000 minutes of free jukebox music in their academic careers at the school A student may select a song from the available collection The user must be able to look up songs by artist and see how long any song takes to play No user may play more than two songs on any given date No song may be played more than ve times on the same date One way to begin building this system is to rst nd the objects Nouns are potential objects We are looking for quotthingsquot that may model the desired system This is not the time to worry about too many details or even if you may be right or wrong A rst pass at nding the objects will represent a list that may end up as part of the system Others will be eliminated And still others may be found later A List of Candidate Objects Jukebox ID card Student Collection Song Date Card reader While trying to discover useful objects it helps to eliminate redundant entries There is no useful purpose for writing down student more than once for example Also you should include only those objects that have meaning within the realm of the system Activity fee funds provide the money to pay for the Jukebox However fees and money need not be developed We do not need to build the student center or keep track of the student s academic careers The seven candidate objects listed above will do for now It is also important to name things as accurately as possible Although the name Student appears many times Student sounds more like an object that might represent the academic career JukeboxAccount better represents this new type SongCollection is more meaningful than collection It is also good to recognize those things that are outside of the system that needs to be developed The software may play a particular song over the stereo system but we do not need to model nor build the stereo systemithis is outside the system It also seems like we could use a way to store all JukeboxAccounts so it is reasonable to list another candidate object named JukeboxAccountCollection 77 The following picture represents another view of these candidate objects and their main responsibilities It also recognizes other parts such as a physical stereo system a card reader and a user all part of the nal system to be controlled by the software we develop Candidate Obiects that Model a Cashless Jukebox the big picture JukeboxAccountCollection Keep track of all accounts CardReader JukeboxAccount Get student ID Keep one student39s history SongCollection Maintain list of all songs Jukebox Song Coordinates Activities Keep song info It helps to consider the main responsibility for each object The responsibilities convey the purpose of an object and its role in the system The proper assignment of responsibilities is an important skill developed over time It can be fuzzy at first People on the development team may disagree It is not exact science it is more about common sense and what makes sense to most people While working on this system consider that each object is responsible for two things 1 What should an object be able to do 2 What should an object remember These responsibilities can be implemented as the methods and the instance variables of a class Designing and Testing Java Classes There are still design decisions to be made and we39ll need a way to know that the classes are doing what they are supposed to be doing To do this we39ll use test driven development Here is a preview of the activities and actual code that will be eXplained in more detail as we progress Activities of Test Driven Development TDD Write a class that will test the code you write later It can begin with a small method with a few assertions that specifies a tiny bit of functionality At this time it appears that a new Song type will need to keep track of it39s title and it playtime 78 Software Deveapmen pumre class SDngTest extends junltfxamewurkTestCase pumre were testGetters Song Song new Sung we een Werk rt Out 135 Sung sungZ new SDng Haxd nsys urgnt 221 assertEquals We asn Werk rt Out sunggetT1tle assertEqualsO S sunggetPlaytuue assertEquals Haxd Dsys lght sung2getT1tle assenEquals22 sung2getPlaytuue Onee me test Exists Wnte enuugh eeae tn successfully tempue the umt test and the class bemg develuped even xfthe assemuns Wm nutpass pumre class Sung pumre Sengstrrng sengmtle rnt playmne pumre strrng getmtleo return TBA pumre rnt getplsytrneo return a Run thetesthth yuurnew eeae U see me test 211 whmh is indicated by aredbarz amp v mshed a ar u 21 semnds Runs 22 llEerrs u lFaHures 2 a Fa ures ltastcettars e SDngTEst EmstcetterSZ e SDngTest Fa ure Trere jumt framewurk caHpensenFeuure Expectad ltWe can Wnrk n Outgt but was ltTBAgt at SDngTest tastGEttEranngTest Java 5 2 The smemshuls shuwn hare may Met rum yuur envnenmem These smemshuls was Epmred rum Eeupse alarm the Mn 3 a 1 tesung Emewurk 79 Then mudAfy the enae tn make the tests pass which wtu be Indicated by a green bar publn class Sung Instance vauames en remember aaea for 1nd1v1dual objects prlvate senng eaele prlvate 1m playTuue Construct Sung objects sn eaen knows 15 2119 and playlng tune publlc SDngStrlng snngmele 1n snngplaymneInSeennas enele snngmele playmne snngplaymneaneennas Pruvlde aeeess en ene eaele of ems Sung publl senng geemeleo return eaele and we how lung 1 W111 take en play ems sung publl 1m getlayt1mamp return playTuue EEerrs u lFaHurEs u n Fa ures 1 me Hteraren FaHurE Trace Themlesnr TDD Wnte thetests rst urlatenfyuu canremember butlt39spusslbleyuu want Try wntang the tests rst Test avary memna mthe class including gamers atleastwnue yuu 311133me Ensure that all tests run getthe greenbzr Yuu may havetn ehange the assemnns because the assemuns are wrungiyuu mistakenly wnte 237 Instead uf 235 fur example 80 Software Development Or you may have to change the code because the method was actually implemented correctly but designed incorrectlyiyou use gt instead of gt for example Bene ts of TDD TDD helps us think about what the software needs to do 0 TDD allows a suite of tests to verify the new type is working 0 The unit tests allow you to refactor which means making small changes to improve your code without changing the meaning 0 You don t need to stare at a bunch of output to guess if the code is correct 0 You can realize that something is wrong and change the software immediately The classes in this chapter will be developed with the aid of the JUnit testing framework developed by Erich Gamma and Kent Beck JUnit is a design and testing tool that is part of many integrated development environments IDE s for Java such as Blue Dr Java and Eclipse Similar tools eXist for designing and testing other popular programming languages such as PHP C C and VBNET Develop design and test One Class One Method at a Time Each Song object should know its title its length in playtime seconds and how often it has been played on the current date This information will be used by other objects in the system We will specify this little bit of functionality as a JUnit test case The minimal code needed to write tests begins as a new class named SongTest To gain access to this testing and development tool the class heading must eXtend the TestCase class from the junit framework package import junitframeworkTestCase public class SongTest extends TestCase the beginning of a unit test with no tests yet SelfCheck 41 In this chapter it helps to type in the code as you are reading The selfchecks for this chapter are limited to typing in all code as it occurs I indicate the new code to be added in boldface Begin with the unit test started above and type in the code as you encounter it In Eclipse Select File gt New gt JUnit Test Case and name it SongTest If asked to add JUnitjar select yes If you do not have Eclipse create a new le named SongTesjava and retype the boldfaced code above you may retype the comment but it s not necessary The reserved identi er extends means that the SongTest class inherits many methods from the class named TestCase in the package junit framework The JUnit framework was designed to help you develop your own classes with minimal effort Here is a review of one of the methods We can compare integer values such as 27 String demoString quotChars between double quotesquot 81 assertEquals27 demoStringlength If the length of demostring the actual value is the expected value 27 the assertion is considered to pass An assertEquals will fail if the eXpected value does not equal the eXpected value The rst argument is the eXpected value and the second argument is the actual value The JUnit testing framework version 38 has a naming convention to recognize a speci c method as a test Junit 4 uses the Test annotation to mark a method as a test You must declare a method as public with a return type of void which means the method returns nothing In Java 38 the method name must begin with test which is case sensitivei Test will not be recognized followed by any number of digits 09 underscores 7 or other letters a z and A Z For example the method name testGetTitle will be recognized as a JUnit test Here is one valid test method written as a stub no code in the body yet public void testGetters NeXt consider what is needed to construct Song objects At this point we know the name of the constructor should be Song but we have to decide which if any values should be sent to the constructor as arguments The test method shows we have decided to have the title as the rst argument and an integer representing the number of seconds of playtime as the second argument Remember that we are writing what we need and we don t care yet if there are compiletime errors At this moment there is no Song class or constructor that takes two arguments a String and an int You will see compiletime errors public void testGetters arguments to the constructor 1 song title 2 playtime in seconds Song songl new SongquotWe Can Work it Outquot 2 60 15 Song song2 new SongquotHard Days Nightquot 221 SelfCheck 42 Add the test method above to the unit test SongTest The following minimal Song class removes the compiletime errors as long as a newly designed constructor is included public class Song public SongString songTitle int songPlayTimeInSeconds SelfCheck 43 Create a new class named Song and add the constructor above Or in Eclipse select the light bulbs and have Eclipse write the code for you 82 Software Development At this point assertions can be made in the test method about the desired state of the object referenced by songl Someone has to give the method a name so let s name it getTitle We could change the name if there were a better one but we won t at this time However we do have to decide if any arguments are required Deciding the arguments part of the design Since we are simply asking the Song objects for the titles no arguments are required in the getTitle method This test method constructs two objects to show that different objects have their own state import junitframeworkTestCase public class SongTest extends TestCase public void testGetters Song songl new SongquotWe Can Work it Outquot 135 Song songZ new SongquotHard Days Nightquot 221 assertEqualsquotWe Can Work it Outquot song1getTitle assertEqualsquotHard Days Nightquot song2getTitle SelfCheck 44 For the remainder of this chapter add the code presented in boldface which includes the two assertions above This is what we want but the getTitle method does not yet eXist This is a normal part of TDD Actually it is part of all other software development strategies but perhaps at different times We have now arrived at the time to remove the compiletime errors and proceed even knowing the assertions may fail Believe it or not TDD proponents want to see the red bar The Song class could now look like this public class Song public SongString songTitle int songPlayTimeInSeconds public String getTitle Return a bogus value to get the red bar return quotneed to store the song title someplacequot Make the assertions fail Now running the unit test will show that the getTitle method does not return the correct value no surprise We eXpected the string value We Can Work it Outquot however the actual value intentionally returned from the method is this need to store the song title someplace If you look closely at the results of the test below you will see there was a test method that failed Failures 1 You will also at the bottom of this screenshot that the eXpected 83 Value ltWe Can Work it up was not the actual Value ltneed to store the song title someplacegt returned from the getTitle method Runs ll EErrurs u EFaliures i EHlerarchy Faliure Trace lg Junit framewurk CDmparisDnFaliure Expected we can Wurk It Outgt but was mad oi stare the sung titie samepTaregt We now need a way for all instances onnc Song class to remember their own song titles Adding instance Variables to the class can do this Make the assertions Pass by adding Instance Variables In general different instances of the samc class remember their own state through instance variables spcclncally adding a titie instance variable to the sang class allows many sang objects to have their own titles The constructor must also assign the argument to the correct instance variable Additionally getTltle must return that remembered value These changes are shown below in the updated sang class that will make both asscm39ons pass thus you should scc the green barinJUnit Can now construct many Song objects with their own title public class Song lnstance variable to remember the title of any song private string title public SongStr1ng sonngtle int songplayTimelnSeconds title songTitle Remember the title passed as an argument public string getTitle return title Return the remembered title for this Song Remember the playing time We can also usc an instance variable to remember the playtime for cacn Song object And we39ll cnoosc getPlayTlme to provide acccss to this information For example the JukeboxAccount will need to deduct the correct amount oni39mc fromits nmc remaining Or the time can be displayed to the user wncn selecting songs Maybe it won t be needed at all Here are two ncw asscm39ons addedto the testmethod 84 Software Development import junitframeworkTestCase public class SongTest extends TestCase public void testGetTitle Song songl new SongquotWe Can Work it Outquot 135 Song songZ new SongquotHard Days Nightquot 221 assertEqualsquotWe Can Work it Outquot songlgetTitle assertEqualsquotHard Days Nightquot songZgetTitle assertEquals135 song1getPlaytime assertEquals221 song2getPlaytime This test method will not compile since getPlayTime is not yet a method in the Song class You might see a compiletime error like this The method getPlayTime is undefined for the type Song Here are the steps now needed to get the code to compile and make the assertions pass 1 Add instance variable playTime to Song so all objects remember their own 2 Initialize this instance variable in the constructor 3 Make the getPlayTime method return the value of this new instance variable public class Song Instance variables private String title 1 Add an instance variable private int playTime public SongString songTitle int songPlayTimeInSeconds title songTitle 2 Initialize instance variable playTime songPlayTimeInSeconds public String getTitle return title public int getPlaytime 3 Return the play time for this object 85 return playTime Add More Functionality One of the requirements for this Jukebox is that no song should be played more than ve times on a given date One way to manage this is to have each Song correctly respond true or false when asked if it can be played today This means we are making the Song responsible for this feature The following test method presents one way to do this Test Driven Development is helping us to design the class It speci es two new methods their names return types and arguments public void testRecordOnePlayAndCanPlay Times played begins at 0 when constructed Song songl new SongquotWe Can Work it Outquot 135 assertTruesonglcanPlayTodayF songlrecordOnePlay songlrecordOnePlay songlrecordOnePlay songlrecordOnePlay assertTruesonglcanPlayTodayF songlrecordOnePlay assertFalsesonglcanPlayToday Your programming environment should have several errors since two methods recordOnePlay and canPlayToday do not yet eXist Using the same approach as above we ll add the methods instance variables and algorithms needed to make these assertions pass The assertion above suggest what should happen during the messages canPlayToday returns true until there have been ve recordOnePlay messages This functionality will be used by another object to either help play the song or to notify the user that the song has been played its maXimum number of times We begin with canPlayToday that does not yet increment songsPlayedToday so it always returns true public class Song Class constant public static final int MAXSONGSPERDAY 5 private int songsPlayedToday public SongString songTitle int songPlayTimeInSeconds songsPlayedToday O public boolean canPlayToday return songsPlayedToday lt MAXSONGSPERDAY 86 Software Development We have to know how to keep track of songsPlayedToday The recordOnePlay method could maintain an array of size MAX7SONGS7PER7DAY to store most recent play dates I tried this and it is quite long Another way to tackle this problem is to keep track of the last day a song has been played Then during a recordOnePlay message the last date played can be compared to the current date If these two are the same date simply increment number of plays by 1 If these two are not the same date this is the rst play of the current date which should be recorded for future comparisons if current date equals the day last played increment the number of plays today by 1 else set day last played to the current date set songs played to l At this point we might need to implement a way to determine the current date and compare it to other dates This could mean implementing another new type That would be a lot of work In eadwe 1metheeX ngjavautilGregorianCalendar Now we need to make sure that songsPlayedToday is correctly updated during a recordOnePlay using the algorithm just proposed First lastPayDate is declared as a javautil GregorianCalendar instance variable as time before songs could be played on a computer lJanuaryl900 import javautilGregorianCalendar Add this instance variable private GregorianCalendar lastPlayDate Add this in the constructor lastPlayDate new GregorianCalendar1900 O 1 Then the rst time a Song is played the lastPlayDate becomes currentDate Since GregorianCalendar objects are equal only if two dates were constructed at the same exact millisecond the following method compares the two dates by year month and day in month don t add this code to Song just yet public void recordOnePlay Get the current month day and year GregorianCalendar currentDate new GregorianCalendar int yl currentDategetGregorianCalendarYEAR int ml currentDategetGregorianCalendarMONTH int dl currentDategetGregorianCalendarDATE Get the month day and year when this song was last played int y2 lastPlayDategetGregorianCalendarYEAR int m2 lastPlayDategetGregorianCalendarMONTH int d2 lastPlayDategetGregorianCalendarDATE 87 if yl y2 ampamp ml m2 ampamp d1 d2 songsPlayedToday else lastPlayDate currentDate songsPlayedToday l Refactoring Refactoring refers to making small changes to existing code without changing its meaning The intention is to make the code more readable The current version of recordOnePlay is dominated by code that checks to see if the last time this song was played was on the current date There is a refactoring named quoteXtract methodquot that suggests you quotTurn the fragment into a method whose name explains the purpose of the methodquot A new private helper method is added that returns true if lastPlayDate is the current date when the message gets sent This makes recordOnePlay easier to read public void recordOnePlay if beenPlayedToday songsPlayedToday else lastPlayDate new GregorianCalendari Today songsPlayedToday 1 private boolean beenPlayedToday Get today39s date from the computer39s clock GregorianCalendar currentDate new GregorianCalendar int yl currentDategetGregorianCa1endarYEAR int m1 currentDategetGregorianCa1endarMONTH int d1 currentDategetGregorianCa1endarDATE int y2 lastPlayDategetGregorianCa1endarYEAR int m2 lastPlayDategetGregorianCa1endarMONTH int d2 lastPlayDategetGregorianCa1endarDATE return yl y2 ampamp m1 m2 ampamp d1 d2 Finishing Song Imagine that we just reread the spec or someone just reminded us that we were supposed to be able to look up songs by artist It also becomes obvious that we will have to actually play the song on the computer It turns out Java can do this given the name of the audio le Therefore each Song object needs to remember the artist and the le name of the audio le Song needs two additional instance variables and two methods to get those values The constructor needs to be changed to allow the additional data Song songl new SongquotBeatlesquot quotHelpquot 132 quotHelpmidquot 88 Software Development The testGetters method can be increased to include assertions for these two methods songs were changed to re ect actual midi les found on the Internet public void testGetters Song songl new SongquotBeatlesquot quotHelpquot 132 quotHelpmidquot Song songZ new SongquotCheryl Crowequot quotHomequot 124 quotHomemidquot assertEqualsquotHelpquot songlgetTitle assertEqualsquotHomequot songZgetTitle assertEqualsquotBeatlesquot songlgetArtist assertEqualsquotCheryl Crowequot songZgetArtist assertEqualsquotHelpmidquot songlgetAudioFileName assertEqualsquotHomemidquot songZgetAudioFileName SelfCheck 45 Replace the testGetters method with the one above We ll also add a toString method to return the artist the title and the playtime as shown in this test method public void testToString Song songl new SongquotBeatlesquot quotHelpquot 132 quotHelpmidquot Song songZ new SongquotCheryl Crowequot quotHomequot 124 quotHomemidquot assertEqualsquotBeatles 39Help39 212quot songltoString assertEqualsquotCheryl Crowe 39Home39 204quot songZtoString The three new methods are shown in this listing of the complete at least for now Song class This class represents one of the Songs that can be played on the cashless Jukebox author Rick Mercer import javautilGregorianCalendar public class Song A class only one for all objects constant can39t be changed public static final int MAXisONGsiPERiDAY 5 Instance variables private String artist private String title private int playTime private String fileName private GregorianCalendar lastPlayDate private int songsPlayedToday Construct a Song object to remember four pieces of information that will be needed by other objects 89 public SongString songArtist String songTitle int songPlayTimeInSeconds String audioFileName artist songArtist title songTitle playTime songPlayTimeInSeconds fileName audioFileName songsPlayedToday 0 lastPlayDate new GregorianCalendar1900 0 l Return the Artist who performed this Song public String getArtist return artist Return the title of this Song public String getTitle return title Return the number of seconds this song will play public int getPlaytime return playTime Return the name of the file containing the actual music The name is not qualified which means a folder name may need to be supplied elsewhere public String getAudioFileName return fileName Returns true if this song has been played less than the maximum times allowed per day which is efined as Song MAXisONGsiPERiDAY public boolean canPlayToday return songsPlayedToday lt MAXisONGsiPERiDAY Update how often this Song has been played on the current date public void recordOnePlay if beenPlayedToday songsPlayedToday else lastPlayDate new GregorianCalendari Today songsPlayedToday l 90 Software Development Return a textual version of this Song user see at the Jukebox Override public String toString Get the playtime as minutesszseconds with a padded 0 int seconds getPlaytime String minsisecs seconds 60 quotzquot if seconds 60 lt 10 minsisecs quot0quot minsisecs quotquot seconds 60 return getArtist quot 39quot getTitle quot39 quot minsisecs l Return true if this song has already been played today private boolean beenPlayedToday GregorianCalendar currentDate new GregorianCalendar int yl currentDategetGregorianCalendarYEAR int ml currentDategetGregorianCalendarMONTH int d1 currentDategetGregorianCalendarDATE int y2 lastPlayDategetGregorianCalendarYEAR int m2 lastPlayDategetGregorianCalendarMONTH int d2 lastPlayDategetGregorianCalendarDATE return yl y2 ampamp ml m2 ampamp dl d2 Pause Actually Playing a Song Without explaining the half dozen new details about playing audio les from a Java application here is a class that will play several audio formats playing mp3 les requires additional installation This is followed by a program that will play the song Help by the Beatles assuming Helpmid is in the correct folder import javaappletApplet import javaappletAudioClip import javanetMalformedURLException import javanetURL public class SongPlayer private String baseFolder private AudioClip audioClip public SongPlayerString baseFolder thisbaseFolder baseFolder l public void playSongSong theSong URL url null try url new URLbaseFolder theSonggetAudioFileName audioClip AppletnewAudioClipurl catch MalformedURLException e Systemoutprintlnquotbad url quot url audioClipplay 97 Flay one Song stored in this folder s miditiles folder import javaxsw1ngJOptlonFaney public class FlayOneMldlSong All songs must be in a folder named miditiles and that folder must be in the same folder as the Java class flies or you won t hear the song play public static flnal string basef older f11el SystemgetFroperty userd1r m1d1f11es y public static void mainltstring1 args SongPlayer theSongPlayer new SongFlayerbaseFoldery Fossslble formats au way alfy mid With extra installation we could play mp3 files Song theSong 7 new Song Eeatles Help 132 Helpm1d y theSongFlayer playSongtheSongy JOptlonPaneshowMessageDlalognull Stop playing theSongtoStr1ngy The SongPlayer starts a new thread that will not be shut down without an explicit call to terminate this program Wlthout this static method call you will have a program running every time you run this program songs playing over the others Systemex1t0 041pm in addition to hearing a midi Version of39Help39 by ch Beatles 6 quot 39 Message Smp playmg Beatles es Help 212 sm SongCollection We need to keep track ofall songs so hey can be shown A SongCollectlon type must be able to do ch following Maintain a collection ofall songs hat can be played Addasong Removeasonghytide 92 Software Development 0 Return an array of songs so it can be shown in a window sorted by Artist then by Title Rick will build this during lecture in C Sc 227 Summer 06 Programming Exercises 4A JukeboxAccount Using TDD implement JukeBoxAccount to represent the student who selects songs Imagine that the Jukebox object that will coordinate activities needs to know if the student can play a song If the student hasn t played two songs on the given date and there is enough time the Jukebox will also need to debit the JukeboxAccount by the playtime of the Song while recording the fact that the student played a song 48 JukeboxAccountCollection Using TDD implement JukeBoxAccountCollection so students can be added removed and found by name 40 Designing an Employee Class Implement a class that represents an hourly employee in the United States who gets paid on a weekly basis Each instance must keep track of an employee s name hourly rate of pay and number of hours worked during the current week A programmer must be able to set the hours worked each week since this changes from week to week Because the time clock measures hours worked in tenths of an hour hours worked must have a fractional part you could make this a double Each Employee object must be able to do the following 0 Find out the employee s name 0 Set the hours worked for the week 0 Determine gross pay rounded to two decimal places Gross pay is de ned as hours worked hourly rate of pay where overtime is 15 the hourly rate for any 0 Compute the social security tax which is de ned as 62 ofgross pay 0 Medicare tax which is de ned as 145 of gross pay Complete a class to provide the requested behavior along with a unit test 4D John Conway39s Game of Life Note This project asks you to implement specific methods in order to allow an author supplied program to show a graphical View of your work The Game of Life was invented by John H Conway to simulate the birth and death of cells in a society The following rules govern the birth andor death of these cells between two consecutive time periods At time T A cell is born if there was none at time Tl and exactly three of its neighbors were alive 93 An existing cell remains alive if at time Tl there were either two or three neighbors A cell dies from isolation if at time Tl there were fewer than two neighbors A cell dies from overcrowding if at time Tl there were more than three neighbors A neighborhood consists of the eight elements around any element 000 O 0 000 The neighborhood can extend to the other side of the society For example a location in the rst row has a neighborhood that includes three locations in the last row The following patterns would occur when T ranges from 1 to 5 with the initial society shown at Tl 0 represents a live cell a blank indicates that no cell exists at the particular location in the society T0 Tl T2 T3 T4 O O O 0 000 O O O O 0 Society dies o at T4 O O O O 0 000 0 000 0 OOO Thispattern repeats O 0 Implement class GameOfLife along with a unit test The methods are speci ed in this project so you can use the graphical user interface shown at the end of this project The methods must exist with the same names parameters and return types For each of the following methods except toString do the following 0 Add a test method rst with calls to nonexistent methods 0 Make the test compile add the method heading and return some bogus return value if necessary 0 See the test fail get the red bar 0 Write the code necessary to make your tests pass For example one simple test method for neighborCount might look like this public void testNeighborsWrapping GameOfLife society new GameOfLife10 16 societygrowCellAt3 0 societygrowCellAt3 15 assertEqualsl societyneighborCount3 15 assertEqualsl societyneighborCount3 0 assertEquals2 societyneighborCount2 0 assertEquals2 societyneighborCount4 0 assertEquals2 societyneighborCount2 15 94 Software Development The required methods are provided with the names in boldface I recommend that you complete one at a time in the order show Write the constructor so it takes two integer arguments to represent the number of rows and columns in the game of life The constructor creates a society with no cells but space to store rowscols cells public GameOfLifeint rows int cols Return the number of usable rows indexed from 0numberOfRows l public int numberOfRows Return the number of columns indexed from 0numberOfColumns l public int numberOfColumns Place a new cell in the society Precondition row and col are in range public void growCellAtint row int col Return one big string of cells to represent the current state of the society of cells see output below where 3939 represents an empty space and 39O39 is a live cell There is no need to test toString Simply use it to visually inspect if needed public String tostring Here is one sample output from toString GameOfLife society new GameOfLife4 l4 societygrowCellAtl 2 societygrowCellAt2 2 societygrowCellAt3 2 SystemoutprintlnsocietytoString Return true if there is a cell at the given row and column Return false if there is none at the specified location public boolean cellAtint row int col Count the neighbors around the given location Use wraparound A cell in row 0 has neighbors in the last row if a cell is in the same column or the column to the left or right In this example oo o o o o o oo cell 05 has two neighbors in the last row cell 28 has four neighbors cell 20 has four neighbors cell 10 has three neighbors The cell at 48 has three neighbors and the cell at 38 has 3 neighbors public int neighborCountint row int col Update the state to represent the next society public void update 95 Run a GUI that uses your GameOfLife Class Once you have finished the GameOlefe type as a Java class see your solution in action by placing the graphical user interface GarneOfLifeGUI39ava into the same project or folder as the GarneOfLifejava you have completed uhn quotMay39s Game 0 Live i quotan jiiiiig IEEEEE IEEEEIEE IE EEEEEEE39 an agar sagas g IE IE HIE HIEEEEEEEE IHEIIIIIIII IHEIIIIIIIII EIIIIIIIII EIIIIIIIIII IIIIIIIIII IIIIIIIIIII IIIIIIIIIIII IIIIIIIIIIIII IIIIIIIIIIIIII IIIIIIIIIIIII IIIIIIIIIIII IIIIIIIIIIII EEEEEEEEEEEE E 39Eiiiiiiiiiiiiiiiiiiiiiiiiii n a a 39 n 1m 2m Inn on sun 5m 7m ann 9m 1m 11m 12m 13m Mun 15m 16m 1m 1m 1m 2m way In mllllsecnnds
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'