22
Chapter 7 Projects 1. [af ter § 7.5 a nd §7.9] Li nke d List ***: Suppose ou !ant to create se"era# o$jects and ou !ant to put the% to&ether in a &roup that can $e accessed throu&h a sin&#e reference "aria$#e. ' po!erfu# !a to do this is to #ink the% a## to&ether in a sin&#e (chain) !here each o$ject is one #ink and each o$ject contains a pointer to the ne+t o$ject. ,his chain is ca##ed a (#inked #ist. ' sin&#e reference points to a header o$ject) this contains a reference that points to the ne+t o$ject) it contains a reference that points to the ne+t o$ject) and so on) unti# the contained reference "aria$#e has a null "a#ue) !hich %eans there is nothin& %ore. -ou can a#!as find e"erthin& in the #ist $ just steppin& throu&h it) fro% one o$ject to the ne+t) unti# ou &et to the fina# null reference. Start $ creatin& a header o$ject and ha"e it point to a null) !hich represents the end of the #ist. ,he reference "aria$#e for the entire #ist a#!as points to this header) and the header points to one of the other/ o$jects in the #ist. 0ne !a to construct a #inked #ist is to %ake the next "aria$#e in each ne! o$ject point to the pre"ious# created o$ject) and update the headers next "aria$#e so that it a#!as  points to the %ost rec ent# created o$ject:  2or e+a%p#e) suppose ou !ant to create a &roup of recipes) #ike those that peop#e !rite on 34 x 54 cards and put into a $o+ in the kitchen. ach recipe is an o$ject of the c#ass descri$ed $ the fo##o!in& 6L c#ass dia&ra%: first o$ject nu## step 1: header o$ject first o$ject nu## second o$ject first o$ject nu## second o$ject third o$ject header o$ject step 8: step 3: header o$ject step : header  o$ject nu##

Chapter 7 Projects

Embed Size (px)

Citation preview

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 1/22

Chapter 7 Projects

1. [after §7.5 and §7.9] Linked List ***:

Suppose ou !ant to create se"era# o$jects and ou !ant to put the% to&ether in a &roup that can $eaccessed throu&h a sin&#e reference "aria$#e. ' po!erfu# !a to do this is to #ink the% a## to&ether ina sin&#e (chain) !here each o$ject is one #ink and each o$ject contains a pointer to the ne+t o$ject.,his chain is ca##ed a (#inked #ist. ' sin&#e reference points to a header o$ject) this contains areference that points to the ne+t o$ject) it contains a reference that points to the ne+t o$ject) and so on)unti# the contained reference "aria$#e has a null "a#ue) !hich %eans there is nothin& %ore. -ou cana#!a s find e"er thin& in the #ist $ just steppin& throu&h it) fro% one o$ject to the ne+t) unti# ou &etto the fina# null reference.

Start $ creatin& a header o$ject and ha"e it point to a null ) !hich represents the end of the #ist. ,hereference "aria$#e for the entire #ist a#!a s points to this header) and the header points to one of the

other/ o$jects in the #ist. 0ne !a to construct a #inked #ist is to %ake the next "aria$#e in each ne!

o$ject point to the pre"ious# created o$ject) and update the header s next "aria$#e so that it a#!a s points to the %ost recent# created o$ject:

2or e+a%p#e) suppose ou !ant to create a &roup of recipes) #ike those that peop#e !rite on 34 x 54cards and put into a $o+ in the kitchen. ach recipe is an o$ject of the c#ass descri$ed $ thefo##o!in& 6 L c#ass dia&ra%:

firsto$ject nu##

step 1:

header o$ject

firsto$ject nu##second

o$ject

firsto$ject nu##second

o$jectthirdo$ject

header o$ject

step 8:

step 3:

header o$ject

step : header o$ject nu##

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 2/22

,he listNames %ethod #ists the name of each o$ject in the #ist) inc#udin& the header. ,he find %ethod returns a reference to the o$ject !hose na%e is the sa%e as the ar&u%ent) $ut if the ar&u%ent

na%e cannot $e found) it returns a nu##. ,he findBefore %ethod returns a reference to the o$jectthat is $efore the o$ject na%ed in the ar&u%ent) $ut if the ar&u%ent na%e cannot $e found) it returns anu##. ,he removeNext %ethod re%o"es fro% the #ist the o$ject that fo##o!s the o$ject ca##in& the%ethod) and it returns a reference to the re%o"ed o$ject. e%o"in& an o$ject e+tracts it fro% the #ist

$ut does not de#ete it. ,he insertAfter %ethod inserts the o$ject ca##in& the %ethod into the #isti%%ediate# after the o$ject referenced $ the ar&u%ent. ,he fo##o!in& dri"er i##ustrates the use ofthese %ethods:

/************************************************************* RecipeDriver.java* Dean & Dean*

* This demonstrates creation and use of a list of recipes.************************************************************/

import java.util.Scanner

pu!lic class RecipeDriver" pu!lic static void main#Strin$% ar$s' " Scanner std(n ) ne Scanner#S+stem.in' Recipe recipes ) null // list header Recipe !efore, current // previous and current o!jects

Recipe recipe- Recipe recipe Recipe recipe Recipe recipe0 Strin$ name

recipes ) ne Recipe#' // a header is re1uired2

recipe- ) ne Recipe#'

;initia#i<e na%e : Strin&) recipe : Strin&/ : "oid;&et=a%e / : Strin&;&et ecipe / : Strin&;&et=e+t / : ecipe;#ist=a%es / : "oid;find na%e : Strin&/ : ecipe;find>efore na%e : Strin&/ : ecipe;re%o"e=e+t / : ecipe;insert'fter pre"ious : ecipe/ : "oid

?na%e : Strin&?recipe : Strin&?ne+t : ecipe

Recipe

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 3/22

recipe ) ne Recipe#' recipe ) ne Recipe#' recipe0 ) ne Recipe#'

recipes.initiali3e#4m+recipes4, 4A Balanced Diet4'

recipe-.initiali3e#4mil54, 4mil5 a co 4 6 47npour mil5 into a !ottle4 6 47nput !ottle into a refri$erator4'

recipe .initiali3e#4ca5e4, 4roll it up, roll it up, thro it in a pan4 6 47n!a5e it in the oven as fast as +ou can4'

recipe .initiali3e#4!eans4, 4fill pan ith ater4 6 47nadd !eans4 6

47n!oil until done and pour off ater4'

recipe0.initiali3e#4jun5food4, 4$o to a store4 6 47n!u+ somethin$ at the chec5out counter4'

recipe-.insertAfter#recipes' recipe .insertAfter#recipes' recipe .insertAfter#recipes' recipe0.insertAfter#recipes'

recipes.listNames#'

do " S+stem.out.print#47n8xtract recipe name9 4' name ) std(n.next:ine#' !efore ) recipes.findBefore#name' ; hile #!efore )) null' S+stem.out.println#4The name !efore that is9 4 6 !efore.$etName#'' current ) !efore.removeNext#' S+stem.out.println#4The name removed is9 4 6 current.$etName#'' S+stem.out.println#4The recipe is97n4 6 current.$etRecipe#''

recipes.listNames#'

do " S+stem.out.print#47n(nsert after recipe name9 4' name ) std(n.next:ine#' !efore ) recipes.find#name'

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 4/22

; hile #!efore )) null' current.insertAfter#!efore'

recipes.listNames#' ; // end main; // end class RecipeDriver

,o re%o"e or insert an o$ject in a #inked #ist) !e need a reference to the o$ject i%%ediate# $efore theo$ject !e care a$out. ,hat s $ecause !e a#!a s ha"e to chan&e the "a#ue of one of the instance"aria$#es the next "aria$#e/ in this precedin& o$ject. ,his #inka&e %ana&e%ent co%p#icates thecode so%e!hat. Perhaps it !i## $e easier to understand !hen ou a#so #ook at a t pica# output.

Sa%p#e session:

Names9m+Recipesjun5food!eans

ca5emil5

8xtract recipe name9 beansThe name !efore that is9 jun5foodThe name removed is9 !eansThe recipe is9fill pan ith ateradd !eans!oil until done and pour off ater

Names9

m+Recipesjun5foodca5emil5

(nsert after recipe name9 milk

Names9m+Recipesjun5foodca5emil5!eans

a/ [after §7.5] @rite code for the Recipe c#ass that confor%s to the 6 L c#ass dia&ra% and a##o!sthe a$o"e dri"er to produce the a$o"e output.

$/ [after §7.9] ,o the Recipe c#ass created in part a/) add a constructor that initia#i<es the o$ject asit is created and auto%atica## inserts it at the head of the #ist A i%%ediate# after the headero$ject. Bon t for&et to pro"ide an e+p#icit no?ar&u%ent constructor a#so) so the e+istin& dri"ersti## !orks. Besi&n this no?ar&u%ent constructor so that it auto%atica## creates the header o$ject.

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 5/22

odif the a$o"e dri"er so that it produces the sa%e sa%p#e session $ usin& the ne!constructors instead of the co%$ination of a"a s defau#t constructor) the initiali3e %ethod)and insertAfter %ethod.

8. [after §7.D ] 'uto%o$i#e Bescription *:

@rite a pro&ra% that asks the user ho! %an auto%o$i#es are to $e descri$ed) and for eachauto%o$i#e it inputs the user s se#ection of %ake and co#or. ,hen it outputs co#or and %ake. '#thou&h

ou cou#d do this easi# usin& a si%p#e procedura# pro&ra%) do it $ usin& a main %ethod in classAutomo!ileDriver to instantiate an o$ject ca##ed auto fro% a class Automo!ile . ake

our c#asses confor% to the fo##o!in& 6 L c#ass dia&ra%:

Let Automo!ile %ethods set<a5e and set=olor do the pro%ptin& and inputtin& for ma5e andcolor ) and inc#ude input "erification !hich asks a&ain if a se#ection is i##e&a#. Let Automo!ile %ethods print=olor and print<a5e print color and ma5e on one #ine. EnAutomo!ileDriver ) after askin& auto to ca## set<a5e and set=olor ) useauto.print=olor#'.print<a5e#' to chain the t!o printin& %ethods. @rite code so thatthe pro&ra% can produce the fo##o!in& disp#a :

Sa%p#e session:

>o man+ cars do +ou ant to consider? 2Select Buic5, =hevrolet, or @ontiac #!,c,p'9 x The onl+ valid selections are ! , c , or pSelect Buic5, =hevrolet, or @ontiac #!,c,p'9 pSelect !lue, $reen, or red #!,$,r'9 r red @ontiacSelect Buic5, =hevrolet, or @ontiac #!,c,p'9 cSelect !lue, $reen, or red #!,$,r'9 g $reen =hevrolet

3. Car$on C c#e ***:

a) [after §7.7] @rite a pair of c#asses for a pro&ra% that %ode#s the car$on c c#e in an ecos ste%.6se t!o &eneric c#asses. 0ne c#ass) 8ntit+ ) defines thin&s. ,he other c#ass) Relationship )defines interactions. Partitionin& e"er thin& into these t!o &enera# cate&ories si%p#ifies the codein each indi"idua# cate&or .

AutomobileDriver

%ain ar&s : Strin&[]/ : "oid

Automobile

set ake / : "oidsetCo#or / : "oid print ake / : "oid printCo#or / : "oid

%ake : Strin&co#or : Strin&

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 6/22

ake our c#asses confor% to this 6 L c#ass dia&ra%:

En the 8ntit+ c#ass) the a#&orith% for the chan$e %ethod is:

accumulation accumulation 6 increment

,he a#&orith% for the do(t %ethod is:

mass mass 6 accumulationif #mass C . ' mass .accumulation

,he idea is to ca#cu#ate a## chan&es $ased on conditions at one particu#ar ti%e. ,hen) after a## thechan&es ha"e $een ca#cu#ated) &o $ack and i%p#e%ent those chan&es. ,his t!o?step processa"oids the inconsistenc that !ou#d occur if ou !ere to i%p#e%ent each chan&e ri&ht after ouca#cu#ated it. Ef ou i%p#e%ented as ou !ent a#on&) so%e chan&es !ou#d $e $ased on ($eforeconditions and other chan&es !ou#d $e $ased on (after conditions.

En the Relationship c#ass) the a#&orith% for the s+nthesi3e %ethod is:

demand time * plant fixin$ rate * plant mass / #- 6 plant mass / plant maximum mass'transfer demand / #- 6 plant mass / atmosphere mass'chan$e atmosphere !+ Etransfer

;set ass a%ount : dou$#e/ : "oid;set ass a+ a%ount : dou$#e/ : "oid;set2i+in&Enput ate rate : dou$#e/ : "oid;set atin&Enput ate rate : dou$#e/ : "oid;set ottin&0utput ate rate : dou$#e/ : "oid;set>reathin&0utput ate rate : dou$#e/ : "oid

;&et ass / : dou$#e;&et ass a+ / : dou$#e;&et2i+in&Enput ate / :dou$#e;&et atin&Enput ate / :dou$#e;&et ottin&0utput ate / :dou$#e;&et>reathin&0utput ate / :dou$#e;chan&e incre%ent: dou$#e/ : "oid;doEt / : "oid

Entity

?fi+in&Enput ate : dou$#e F ?eatin&Enput ate : dou$#e F ?rottin&0utput ate : dou$#e F ?$reathin&0utput ate : dou$#e F ?%ass a+ : dou$#e F 1. e1?%ass : dou$#e?accu%u#ation : dou$#e F

Relationship

;s nthesi<e at%osphere : ntit ) p#ants : ntit ) ti%e : dou$#e/ : "oid;eat p#ants : ntit ) ani%a#s : ntit ) ti%e : dou$#e/ : "oid;rot p#ants : ntit ) ani%a#s : ntit ) $acteria : ntit ) ti%e : dou$#e/ : "oid;$reathe p#ants : ntit ) ani%a#s : ntit ) $acteria : ntit ) at%osphere : ntit ) ti%e : dou$#e/ : "oid

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 7/22

chan$e plants !+ 6transfer

,he a#&orith% for the eat %ethod is:

demand time * animal eatin$ rate * animal masstransfer demand / #- 6 animal mass / plant mass'chan$e plants !+ Etransferchan$e animals !+ 6transfer

,he a#&orith% for the rot %ethod is:

transfer time * plant rottin$ rate * plant masschan$e plants !+ Etransferchan$e !acteria !+ 6transfertransfer time * animal rottin$ rate * animal masschan$e animals !+ Etransferchan$e !acteria !+ 6transfer

,he a#&orith% for the !reathe %ethod is:

transfer time * plant !reathin$ rate * plant masschan$e plants !+ Etransferchan$e atmosphere !+ 6transfertransfer time * animal !reathin$ rate * animal masschan$e animals !+ Etransferchan$e atmosphere !+ 6transfertransfer time * !acteria !reathin$ rate * !acteria masschan$e !acteria !+ Etransferchan$e atmosphere !+ 6transfer

,his dri"er shou#d produce the output that fo##o!s it:

/************************************************************** =ar!on=+cleDriver.java* Dean & Dean** This drives 8ntities ho are mem!ers of a food e!.* All Relationships are some 5ind of car!on transfer9* #-' photos+nthesis9 plants ta5e from atmosphere* # ' eatin$9 animals ta5e from plants* # ' rottin$9 plants & animals $ive to !acteria* #0' !reathin$9 plants, animals, !acteria $ive to atmosphere

*************************************************************/import java.util.Scanner

pu!lic class =ar!on=+cleDriver" pu!lic static void main#Strin$% ar$s' " Scanner std(n ) ne Scanner#S+stem.in'

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 8/22

int steps // total num!er of simulation steps dou!le timeStep // time increment in each step dou!le demand // amount demanded in particular step dou!le transfer // amount transferred !et een entities

Relationship car!on ) ne Relationship#'

8ntit+ atmosphere ) ne 8ntit+#' 8ntit+ plants ) ne 8ntit+#' 8ntit+ animals ) ne 8ntit+#' 8ntit+ !acteria ) ne 8ntit+#'

// confi$ure and initiali3e s+stem

// initiali3e causal per unit rate parameters plants.setFixin$(nputRate# . ' plants.setRottin$GutputRate# . H' plants.setBreathin$GutputRate# . H' animals.set8atin$(nputRate# . -'

animals.setRottin$GutputRate# . -' animals.setBreathin$GutputRate# . -' !acteria.setBreathin$GutputRate# . H'

// initiali3e entit+ constraint and state varia!les plants.set<ass<ax#H . ' atmosphere.set<ass#- . ' plants.set<ass#- . ' animals.set<ass#- . ' !acteria.set<ass#- . '

// set up simulation S+stem.out.print#48nter si3e of time step # .- to '9 4' timeStep ) std(n.nextDou!le#' S+stem.out.print#48nter total num!er of steps9 4' steps ) std(n.next(nt#'

// do simulation for #int step) stepCsteps step66' " // evaluate interEentit+ transfers !ased on old states

// #-' plants ta5e from atmosphere, as availa!le car!on.s+nthesi3e#atmosphere, plants, timeStep'

// # ' animals ta5e from plants, as availa!le car!on.eat#plants, animals, timeStep'

// # ' plants and animals $ive to !acteria car!on.rot#plants, animals, !acteria, timeStep'

// #0' plants animals and !acteria $ive to atmosphere car!on.!reathe#plants, animals, !acteria, atmosphere, timeStep'

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 9/22

// update entit+ states ith accumulated chan$es atmosphere.do(t#' plants.do(t#' animals.do(t#' !acteria.do(t#'

// output as int for reada!ilit+ S+stem.out.println# 4atmosphere) 4 6 #int' atmosphere.$et<ass#' 6 4 plants) 4 6 #int' plants.$et<ass#' 6 4 animals) 4 6 #int' animals.$et<ass#' 6 4 !acteria) 4 6 #int' !acteria.$et<ass#'' ; // end for ; // end main; // end class =ar!on=+cleDriver

Sa%p#e session:

8nter si3e of time step # .- to '9 308nter total num!er of steps9 10atmosphere) - H plants) I0 animals) - !acteria) -atmosphere) -- plants) I H animals) - !acteria) Iatmosphere) -- J plants) KJI animals) - !acteria) Iatmosphere) --0K plants) KL- animals) - !acteria) KKatmosphere) --L plants) K0J animals) -- !acteria) KJatmosphere) --J plants) K K animals) -- !acteria) KLatmosphere) --K- plants) K animals) -- !acteria) KHatmosphere) --KJ plants) K H animals) -- !acteria) KHatmosphere) --I- plants) K - animals) - !acteria) K0atmosphere) --IH plants) K-J animals) - !acteria) K0

b) [after §7.9] e"ise the dri"er and 8ntit+ c#asses to shift a## of the initia#i<ation operations to8ntit+ constructors.

G. [after §7.H] EP 'ddress *:

"er co%puter on the Enternet has a uniIue identif in& nu%$er) ca##ed an Enternet protoco# EP/ address.,o contact a co%puter on the Enternet) ou send a %essa&e to the co%puter s EP address. Jere are so%et pica# EP addresses:

81D.87.D.13D88G. .11H.D8

,here are different for%ats for disp#a in& EP addresses) $ut the %ost co%%on for%at is the dotteddeci%a# for%at. ,he a$o"e t!o EP addresses use the dotted?deci%a# for%at. Et s ca##ed (dotted $ecausedots are used to sp#it up the $i& EP address nu%$er into four s%a##er nu%$ers. Et s ca##ed (deci%a#

$ecause deci%a# nu%$ers are used as opposed to $inar / for the four s%a##er nu%$ers.

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 10/22

ach of the four s%a##er nu%$ers is ca##ed an octet $ecause each nu%$er represents ei&ht $its oct %eansei&ht/. 2or e+a%p#e) the 81D octet represents 11 11 and the 87 octet represents 11 11.

E%p#e%ent an (pAddress c#ass that stores an EP address as a dotted?deci%a# strin& and as four octetint s.

-ou %ust i%p#e%ent a## of the fo##o!in&:

Enstance "aria$#es:dottedDecimal A a dotted?deci%a# strin&. +a%p#e "a#ue: 4 -L. J.L.- L4firstGctet ) secondGctet ) thirdGctet ) fourthGctet A four int "aria$#es that store theoctets for an EP address

Constructor:,his constructor recei"es one para%eter) a dotted?deci%a# strin&. -ou %a assu%e that the para%eter s"a#ue is "a#id i.e.) no error checkin& reIuired/. ,he constructor initia#i<es the instance "aria$#es !ithappropriate "a#ues. ,here are %an !a s to so#"e the pro$#e% of e+tractin& octets fro% the &i"en dotted?deci%a# strin&. @e reco%%end that ou use Strin$ %ethods to e+tract the indi"idua# octets as strin&s)and then use parse(nt %ethod ca##s to con"ert the octet strin&s to int s.

$etDottedDecimal %ethod:,his is a standard accessor %ethod that si%p# returns the dottedDecimal instance "aria$#e s "a#ue.

$etGctet %ethod:,his %ethod recei"es the position of one of the octets 1) 8) 3) or G/ and returns the octet that s at that

position.

Pro"ide a dri"er c#ass that tests our (pAddress c#ass. -our dri"er c#ass shou#d contain this main %ethod:

pu!lic static void main#Strin$% ar$s'" (pAddress ip ) ne (pAddress#4 -L. J.L.- L4' S+stem.out.println#ip.$etDottedDecimal#'' S+stem.out.println#ip.$etGctet#0'' S+stem.out.println#ip.$etGctet#-'' S+stem.out.println#ip.$etGctet# '' S+stem.out.println#ip.$etGctet# ''; // end main

6sin& the a$o"e main %ethod) our pro&ra% shou#d &enerate the fo##o!in& output.

Sa%p#e output:

-L. J.L.- L- L

-LL

J

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 11/22

5. [after §7.9] 2raction Jand#er **:

a/ @rite a Fraction c#ass that i%p#e%ents these %ethods:

• add K ,his %ethod recei"es a Fraction para%eter and adds the para%eter fraction to the

ca##in& o$ject fraction.• multipl+ K ,his %ethod recei"es a Fraction para%eter and %u#tip#ies the para%eter

fraction $ the ca##in& o$ject fraction.

• print K ,his %ethod prints the fraction usin& fraction notation 1 G) 81 1G) etc./

• printAsDou!le K ,his %ethod prints the fraction as a dou$#e .85) 1.5) etc./

Separate accessor %ethods for each instance "aria$#e in the Fraction c#ass.

Pro"ide a dri"er c#ass) FractionDemo ) that de%onstrates this Fraction c#ass. ,he dri"er c#assshou#d contain this main %ethod:

pu!lic static void main#Strin$% ar$s'" Scanner std(n ) ne Scanner#S+stem.in' Fraction c, d, x // Fraction o!jects

S+stem.out.println#48nter numerator then denominator.4' c ) ne Fraction#std(n.next(nt#', std(n.next(nt#'' c.print#'

S+stem.out.println#48nter numerator then denominator.4' d ) ne Fraction#std(n.next(nt#', std(n.next(nt#'' d.print#'

x ) ne Fraction#' // create a fraction for num!er

S+stem.out.println#4Sum94' x.add#c'.add#d' x.print#' x.printAsDou!le#'

x ) ne Fraction#-, -' // create a fraction for num!er -

S+stem.out.println#4@roduct94' x.multipl+#c'.multipl+#d'

x.print#' x.printAsDou!le#'

S+stem.out.println#48nter numerator then denominator.4' x ) ne Fraction#std(n.next(nt#', std(n.next(nt#'' x.printAsDou!le#'; // end main

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 12/22

=ote that this de%onstration dri"er does not ca## the accessor %ethods. ,hat s 0M. 'ccessor %ethodsare often i%p#e%ented re&ard#ess of !hether there s an i%%ediate need for the%. ,hat s $ecausethe are "er usefu# %ethods in &enera# and pro"idin& the% %eans that future code can use the%!hen the need arises.

Sa%p#e session:

8nter numerator then denominator.58H/K8nter numerator then denominator.4100/-Sum9K /K-. H

@roduct9/K. H

8nter numerator then denominator.6 0infinit+

$/ odif the code so that it can hand#e ne&ati"e nu%erators and ne&ati"e deno%inators) and pro"ide a he#pin& %ethod that perfor%s fraction reduction.

Sa%p#e session usin& ne&ati"e nu%$ers and reduction:

8nter numerator then denominator.-5-8H/K8nter numerator then denominator.4-10E /HSum9I/0

. H@roduct9E-/0E . H8nter numerator then denominator.0-0indeterminate

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 13/22

D. [after §7.1 ] #ectric Circuit **:

Consider a si%p#e e#ectric circuit that has $ranches and nodes. >ranches connect nodes. ach $ranchhas an inductance %easured in Jenries/ in series !ith a resistance %easured in 0h%s/. ,he "o#ta&edrop across the co%$ination is the inductance in Jenr s ti%es the rate of chan&e in current per unitti%e a%ps per second/ p#us the current a%ps/ ti%es the resistance oh%s/. ach node has acapacitance %easured in 2arads/ &oin& fro% the node to a co%%on &round. ,his circuit is usefu# for#o!?pass fi#ters K fi#ters that e#i%inate hi&h?freIuenc noise. Jere is a dri"er that confi&ures and e+ercises a $a#anced?, #o!?pass fi#ter circuit:

/************************************************************** 8lectric=ircuitDriver.java* Dean & Dean** This class drives the Branch and Node classes to* confi$ure and simulate a TEt+pe lo Epass filter.*************************************************************/

import java.util.Scanner

pu!lic class 8lectric=ircuitDriver" pu!lic static void main#Strin$% ar$s' " Scanner std(n ) ne Scanner#S+stem.in' dou!le timeStep ) -. 8EH int steps // max steps int output(nterval // steps !et een outputs

// confi$ure circuit Node node- ) ne Node#' Node node ) ne Node#' Branch !ranchA ) ne Branch#' Branch !ranchB ) ne Branch#'

node .setFarads#-. eEJ' // .- microfarad !ranchA.setFrom#node-' !ranchA.setTo#node ' !ranchA.set>enr+s#-. eE ' // -. millihenr+ !ranchA.setGhms#- . ' !ranchB.setFrom#node ' // To $round !ranchB.set>enr+s#-. eE ' !ranchB.setGhms#- . '

S+stem.out.print#48nter seconds per timeStep#C-. 8EK'9 4' timeStep ) std(n.nextDou!le#' S+stem.out.print#48nter num!er of steps#-H ?'9 4' steps ) std(n.next(nt#' S+stem.out.print#48nter steps per output#- ?'9 4' output(nterval ) std(n.next(nt#'

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 14/22

node-.setMolts#-. ' for #int step) stepCsteps step66' " // compute chan$es !ranchA.accumulate#timeStep'

!ranchB.accumulate#timeStep' node .accumulate#timeStep, !ranchA.$etAmps#'' node .accumulate#timeStep, E!ranchB.$etAmps#''

// implement chan$es !ranchA.do(t#' !ranchB.do(t#' node .do(t#'

// displa+ output if #step output(nterval )) ' "

S+stem.out.println#4at time ) 4 6 #int' #-.8L * step * timeStep' 6 4 microseconds9 :oad volts) 4 6 #int' #-.8 * !ranchB.$etAmps#' * !ranchB.$etGhms#'' 6 4 millivolts4' ; ; // end for ; // end main; // end 8lectric=ircuitDriver class

,he dri"er creates and e+ercises the fo##o!in& circuit:

Befine c#asses for nodes and $ranches in accordance !ith the fo##o!in& 6 L dia&ra%:

!ranchASourceresistance

1 0h%s/

2i#terinductance

1. %J/

!ranchB2i#ter inductance

1. %J/

Loadresistance

1 0h%s/Load"o#ta&e

node- node

Capacitance%icro2arad

1E"o#t step

Nround node

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 15/22

,he node s accumulate %ethod accu%u#ates "o#ta&e chan&e in one ti%e incre%ent) usin& thecurrent at the $e&innin& of that ti%e incre%ent. Ets a#&orith% is:

accumulation accumulation 6 timeStep * amps / farads

,he a#&orith% for the Node.do(t %ethod is:

volts volts 6 accumulationaccumulation

,he $ranch s accumulate %ethod co%putes current chan&e in one ti%e incre%ent) usin& "o#ta&esand current at the $e&innin& of that ti%e incre%ent. Ef the Node para%eter is null ) thecorrespondin& volts F . . 0ther!ise) it is the volts of that node. ,he "o#ta&e drop is the from node "o#ts %inus the to node "o#ts. Ets a#&orith% is:

accumulation accumulation 6 timeStep * ##fromMolts E toMolts' E amps * ohms' / henr+s

,he a#&orith% for the Branch.do(t %ethod is:

amps amps 6 accumulationaccumulation

Sa%p#e session:

8nter seconds per timeStep#C-. 8EK'9 1e-88nter num!er of steps#-H ?'9 150008nter steps per output#- ?'9 1000at time ) microseconds9 :oad volts) millivoltsat time ) - microseconds9 :oad volts) I millivoltsat time ) microseconds9 :oad volts) LL millivolts

;set2arads farads : dou$#e/ : "oid;setOo#ts "o#ts : dou$#e/ : "oid;&etOo#ts / : dou$#e;accu%u#ate ti%eStep : dou$#e) a%ps : dou$#e/ : "oid;doEt / : "oid

Node

?farads : dou$#e F 1. ?18?accu%u#ation : dou$#e F .?"o#ts : dou$#e F .

Branch

?fro% : =ode?to : =ode?henries : dou$#e F 1. ?9?oh%s : dou$#e F .

?accu%u#ation : dou$#e F .?a%ps : dou$#e F .

;set2ro% fro% : =ode/ : "oid;set,o to : =ode/ : "oid;setJenr s henr s : dou$#e/ : "oid;set0h%s oh%s : dou$#e/ : "oid;set'%ps a%ps : dou$#e/ : "oid;&et0h%s / : dou$#e;&et'%ps / : dou$#e;accu%u#ate ti%eStep : dou$#e/ : "oid;doEt / : "oid

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 16/22

at time ) microseconds9 :oad volts) H J millivoltsat time ) 0 microseconds9 :oad volts) H millivoltsat time ) H microseconds9 :oad volts) 0KL millivoltsat time ) L microseconds9 :oad volts) 0JI millivoltsat time ) J microseconds9 :oad volts) 0IJ millivoltsat time ) K microseconds9 :oad volts) H L millivolts

at time ) I microseconds9 :oad volts) H millivoltsat time ) - microseconds9 :oad volts) 0IK millivoltsat time ) -- microseconds9 :oad volts) 0IK millivoltsat time ) - microseconds9 :oad volts) H millivoltsat time ) - microseconds9 :oad volts) H millivoltsat time ) -0 microseconds9 :oad volts) H millivolts

7. [after §7.1 ] Cost 'ccountin& ***:

@rite an o$ject?oriented pro&ra% that de%onstrates cost accountin& in a %anufacturin& p#ant. akethe pro&ra% produce the fo##o!in& output.

0utput:

Assets cash L,K . ra material 0, . or5 in process . finished $oods .:ia!ilities a$es pa+a!le .Net Oorth e1uit+ #- , . '

Revenue sales # ,L . '8xpenses material expense H . la!or expense L . overhead expense .

jo! record of or5 in process ) .

0r&ani<e the code in accordance !ith this 6 L c#ass dia&ra%:

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 17/22

En the dri"er c#ass) the main %ethod is:pu!lic static void main#Strin$% ar$s'" dou!le amount // a or5in$ varia!le

=ostAccountin$ accounts ) ne =ostAccountin$#' Po! jo!- Po! jo!

// esta!lish !usiness accounts.invest#- .' accounts.purchase#H .'

// manufacture products jo!- ) ne Po!#accounts, H ., L ., .' jo! ) ne Po!#accounts, ., , ' jo!-.finish#' accounts.pa+Oa$es#'

// sell all finished products

CostAccountingDriver

;%ain ar&s : Strin&/ : "oid

Account

?$a#ance : dou$#e F

;de$it a%ount : dou$#e/ : "oid;credit a%ount : dou$#e/ : "oid;&et>a#ance / : dou$#e

Job

?accounts : Cost'ccountin&?%ateria# : dou$#e F .?#a$or : dou$#e F .?o"erhead : dou$#e F .?status : char F p

; o$ accounts : Cost'ccountin&) %ateria# : dou$#e) #a$or : dou$#e) o"erhead : dou$#e/;finish / : "oid;&et ateria# / : dou$#e;&etLa$or / : dou$#e;&et0"erhead / : dou$#e;&etStatus / : char ;findCost / : dou$#e;setStatus status : char/ : "oid

CostAccounting

?cash : 'ccount?ra! ateria# : 'ccount?!orkEnProcess : 'ccount?finishedNoods : 'ccount?!a&esPa a$#e : 'ccount?eIuit : 'ccount?sa#es : 'ccount?%ateria# +pense : 'ccount?#a$or +pense : 'ccount?o"erhead +pense : 'ccount

;&et a! ateria# / : 'ccount;&et@orkEnProcess / : 'ccount;&et2inishedNoods / : 'ccount;&et@a&esPa a$#e / : 'ccount;in"est a%ount : dou$#e/ : "oid;purchase a%ount : dou$#e/ : "oid;pa @a&es / : "oid;se## jo$ : o$) factor : dou$#e/ : "oid;$a#ance / : "oid

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 18/22

if #jo!-.$etStatus#' )) f ' " accounts.sell#jo!-, . ' ; if #jo! .$etStatus#' )) f ' "

accounts.sell#jo! , . ' ;

// do trial !alance accounts.!alance#'

// or5 in process reconciliation amount ) if #jo!-.$etStatus#' )) p ' " amount 6) jo!-.find=ost#' ;

if #jo! .$etStatus#' )) p ' " amount 6) jo! .find=ost#' ; S+stem.out.println# 47njo! record of or5 in process ) 4 6 amount'; // end main

En the =ostAccountin$ c#ass) a## the instance "aria$#es shou#d $e references to o$jects of theAccount c#ass. ,he invest %ethod shou#d de$it cash and credits e1uit+ . ,he purchase %ethod shou#d de$it ra <aterial and credit cash . ,he pa+Oa$es %ethod shou#d credit cash and de$it a$es@a+a!le $ the a%ount of a$es@a+a!le . ,he sell %ethod shou#d set jo$

status to Qs ) de$itmaterial8xpense $ jo$ material ) de$it la!or8xpense $ jo$la!or ) and de$it overhead8xpense $ jo$ overhead . Et shou#d credit finishedQoods $the tota# jo$ cost) and it shou#d de$it cash and credit sales $ that a%ount ti%es the factor

passed into sell as an ar&u%ent. ,he !alance %ethod shou#d use the printf %ethod to round%one to the nearest penn . Ensert co%%as and use parentheses for ne&ati"e "a#ues.

En the Po! c#ass) the constructor shou#d start a ne! jo$ $ storin& a reference to the o$ject thatcontains references to a## &enera# accounts) and storin& the a%ounts of indi"idua# jo$ %ateria#) #a$or)and o"erhead. ,he constructor a#so shou#d de$it or5(n@rocess and credit ra <aterial $the a%ount of %ateria#) and it shou#d de$it or5(n@rocess and credit a$es@a+a!le $ thetota# of #a$or and o"erhead. ,he finish %ethod shou#d credit or5(n@rocess and de$itfinishedQoods $ the tota# jo$ cost %ateria# ; #a$or ; o"erhead/) and it shou#d set status to Qf .

H. [after §7.1 ] Po#itica# Ca%pai&n ***:

,his is Chapter 3 s Project H so#"ed in a different !a . > passin& reference "aria$#es in ar&u%ents!e do a $etter jo$ of %odu#ari<in& the code and &reat# si%p#if the main %ethod. ,his projectinc#udes se"era# e+a%p#es of o"er#oaded %ethods and o"er#oaded constructors.

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 19/22

Jere is the dri"er:

/************************************************************* @olitical=ampai$nDriver.java* Dean & Dean*

* This pro$ram $athers statistics and expected pro!a!ilities.* (t projects votes in various votin$ cate$ories, estimates* funds that ill !e raised, and estimates num!er of or5* hours that ill !e re1uired. (t uses the class* @olitical=ampai$n, hich uses classes Moters and Oor5ers.************************************************************/

pu!lic class @olitical=ampai$nDriver" pu!lic static void main#Strin$% ar$s' " @olitical=ampai$n campai$n ) ne @olitical=ampai$n#'

campai$n.$atherData#' campai$n.evaluate@rospects#' campai$n.!ud$et<one+#' campai$n.planTime#' ; // end main; // end class @olitical=ampai$nDriver

@rite c#asses @olitical=ampai$n ) Moter ) and Oor5er so that the o"era## pro&ra% is a$#e to&enerate the fo##o!in& disp#a .

Sa%p#e session:

@G:(T(=A: =A<@A(QN @:ANN8R

8nter total re$istered voters9 50008nter our part+ re$istered voters9 15008nter independent re$istered voters9 20008nter our part+ re$ular re$istered voters9 9008nter independent re$ular re$istered voters9 10008nter expected total turnout9 2000

8nter our part+ re$ular favora!le votes9 1.08nter independent re$ular favora!le votes9 0.58nter our part+ occasional favora!le votes9 0.6 8nter other favora!le votes9 0.1

8xpected votes9Re$ular part+ votes ) J0IRe$ular independent votes ) 0-LGccasional part+ votes ) 0KGther votes ) total expected votes ) - 0L

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 20/22

votes needed ) - -

8nter num!er of or5ers availa!le9 25

8xpected Fundin$98nter num!er of earl+ H donors9 4

8nter num!er of solicitation calls9 50Amount availa!le for campai$n ) H .

Oor5 @lan9=all first pool? %+es9-, no9 9 1=all second pool? %+es9-, no9 9 1=all third pool? %+es9-, no9 9 08nter num!er of pollin$ places9 2

=lerical hours ) IH.Telephone hours ) .@oll atcher hours ) .

Transport hours ) IH.Gverhead hours ) - .HTotal or5er hours ) H- .H>ours per or5er )

ake these c#asses confor% to the fo##o!in& 6 L c#ass dia&ra%:

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 21/22

En c#ass@olitical=ampai$n ) the constructor instantiates a Moter o$ject for each Moter reference "aria$#e. Et uses the constructor !ith the Strin$ ar&u%ent for a## $ut the #ast t!o Moter o$jects.

,he $atherData %ethod sets the turnout in total . Et sets the %a+i%u% inour@art+Gccasionals usin& the a#&orith%:maximum our@art+ maximum our@art+Re$ulars maximum

Et sets the %a+i%u% in others usin& the a#&orith%:maximum total maximum our@art+Re$ulars maximum independentRe$ulars maximum our@art+Gccasionals maximumEt sets the fa"ora$#e fraction in our@art+Re$ulars ) independentRe$ulars )our@art+Gccasionals ) and other . Et sets the no?ar&u%ent "ersion to set turnout inour@art+Re$ulars and independentRe$ulars . Et uses the dou!le ?ar&u%ent "ersion toset turnout in our@art+Gccasionals and others ) !here the ar&u%ent is:

PoliticalCampaignDriver

;%ain ar&s : Strin&/ : "oid

Workers

?CL EC'LRJ06 SRP RC'LL : dou$#e F . 5?, '=SP0 ,RJ06 SRP RC'LL : dou$#e F . 5?0O J 'BR2 'C,E0= : dou$#e F .85?!orkers : int F 85?te#ephoneCa##er,i%e : dou$#e F .

;@orkers !orkers : int/;set,e#ephoneCa##er,i%e ti%e : dou$#e/ : "oid;&et,e#ephoneCa##er,i%e / : dou$#e;p#an,i%e ca##s: dou$#e/ : "oid

oters

? N6L' R,6 =06,R2 'C,E0= : dou$#e F .H33?%a+i%u% : int?turnout : int

?fa"ora$#e : dou$#e

;Ooters /;Ooters t pe : Strin&/;set a+i%u% %a+i%u% : int/ : "oid;set,urnout turnout : int/ : "oid;set,urnout / : "oid;set,urnout fraction : dou$#e/ : "oid;set2a"ora$#e fraction : dou$#e/ : "oid;set2a"ora$#e t pe : Strin&/ : "oid;&et a+i%u% / : int;&et,urnout / : int;findOotes / : int

PoliticalCampaign

?B0LL' SRP RS0LECE,',E0= : dou$#e F 5.?, L PJ0= RJ06 SRP RC'LL : dou$#e F .1?tota# : Ooters?ourPart : Ooters?independent : Ooters?ourPart e&u#ars : Ooters?independent e&u#ars : Ooters

?ourPart 0ccasiona#s : Ooters?others : Ooters?!orkers : @orkers?$ud&et : dou$#e?ca##s : int

;Po#itica#Ca%pai&n /;&atherBata / : "oid;e"a#uateProspects / : "oid;$ud&et one / : "oid;p#an,i%e / : "oid

8/16/2019 Chapter 7 Projects

http://slidepdf.com/reader/full/chapter-7-projects 22/22

fraction #total turnout our@art+Re$ulars turnout independentRe$ulars turnout' / #re$istered total re$isteredour@art+Re$ulars re$istered independentRe$ulars'

,he evaluate@rospects %ethod uses the findMotes %ethod in the Moter c#ass to print thee+pected "otes in each "otin& poo#) and accu%u#ates the% to o$tain e+pected tota# "otes. ,he "otesneeded to !in is one %ore than ha#f of the tota# "otes.

,he !ud$et<one+ %ethod &athers data to esti%ate %one a"ai#a$#e) usin& the a#&orith%:!ud$et earl+ donors * H . 6 calls * dollars per solicitationEt a#so initia#i<es !orkers te#ephone ca##er ti%e usin& the a#&orith%:telephone caller time . * calls * telephone hours per call

,he planTime %ethod %u#tip#ies an input 1 or <ero ti%es the tota# nu%$er of peop#e in each of the poo#s: our@art+Re$ulars ) independentRe$ulars ) and our@art+Gccasionals . ,henit %u#tip#ies the su% of these products $ te#ephone hours per ca## to &et additiona# te#ephone ca##erti%e. 6sin& a 1 or <ero input for a factor either inc#udes or doesn t inc#ude a particu#ar cate&or in asu%%ation./ ,he planTime %ethod in @olitical=ampai$n de#e&ates rest of the p#annin& tothe !orkers $ ca##in& the planTime %ethod in the Oor5ers c#ass.

,he Moters c#ass defines o$jects that descri$e the "arious "oter poo#s. ,he Strin$ ?ar&u%entconstructor initia#i<es maximum $ askin& the user to pro"ide the nu%$er of re&istered "oters in each

poo#. ,he <ero?ar&u%ent setTurnout %ethod co%putes the turnout as the product of maximum and the re&u#ar turnout fraction. ,he dou$#e?ar&u%ent setTurnout %ethod co%putes the turnout asthe product of maximum and the supp#ied fraction. ,he Strin$ ?ar&u%ent setFavora!le %ethoduses the ar&u%ent in a pro%pt to he#p the user supp# an input "a#ue. ,he findMotes %ethodreturns the product of turnout and fa"ora$#e fraction.

En the Oor5ers c#ass) the planTime %ethod ca#cu#ates c#erica# ti%e $ %u#tip# in& input calls $ c#erica# hours per ca##. Et ca#cu#ates po## !atcher ti%e usin& the a#&orith%:poll atcher time - . * num!er of pollin$ placesPo## !atchers ha"e check #ists to keep track of !ho has not et "oted so that te#ephone ca##ers at partheadIuarters can dispatch transport !orkers to he#p &et friend# "oters to the po##s. ,his %ethod a#soca#cu#ates ti%e to transport o#d and infir% friend# "oters to the po##in& p#aces $ %u#tip# in& inputcalls $ transport hours per ca##. 0"erhead hours is c#erica# ti%e) te#ephone ca##er ti%e) po##!atcher ti%e) and transport ti%e/ ti%es the assu%ed o"erhead fraction) and !e add these o"erheadhours to the other hours to o$tain the tota# ti%e printed out.