chapter 1 programing

180
Chapter 1 programin g HelloWorld.java Below is the syntax highlighted version of HelloWorld.java  from §1.1 Hello World. /*************************************************************************  * Compilation: javac HelloWorld.java  * Execution: java HelloWorld  *  * Prints "Hello, World". By tradition, tis is everyone!s irst pro#ram.  *  * $ java HelloWorld  * Hello, World  *  * %ese &' lines o text are comments. %ey are not part o te pro#ram(  * tey serve to remind us a)out its properties. %e irst to lines tell  * us at to type to compile and test te pro#ram. %e next line descri)es  * te purpose o te pro#ram. %e next e lines #ive a sample execution  * o te pro#ram and te resultin# output. We ill alays include suc * lines in our pro#rams and encoura#e you to do te same.  *  *************************************************************************/ pu)lic class HelloWorld +  pu)lic static void main-trin# ar#s0 +  -ystem.out.println"Hello, World"0(  1 1 UseArgument.java Below is the syntax highlighted version of UseArgument.java  from §1.1 Hello World. /*************************************************************************  * Compilation: javac 2se3r#ument.java  * Execution: java 2se3r#ument yourname  *

Upload: ashu

Post on 01-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 1/180

Chapter 1 programing

HelloWorld.javaBelow is the syntax highlighted version of HelloWorld.java from §1.1 Hello World.

/************************************************************************* * Compilation: javac HelloWorld.java * Execution: java HelloWorld * * Prints "Hello, World". By tradition, tis is everyone!s irst pro#ram.

 * * $ java HelloWorld * Hello, World * * %ese &' lines o text are comments. %ey are not part o te pro#ram( * tey serve to remind us a)out its properties. %e irst to lines tell * us at to type to compile and test te pro#ram. %e next line descri)es * te purpose o te pro#ram. %e next e lines #ive a sample execution * o te pro#ram and te resultin# output. We ill alays include suc* lines in our pro#rams and encoura#e you to do te same. *  *************************************************************************/

pu)lic class HelloWorld +

  pu)lic static void main-trin# ar#s0 +  -ystem.out.println"Hello, World"0(  1

1

UseArgument.java

Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World.

/************************************************************************* * Compilation: javac 2se3r#ument.java * Execution: java 2se3r#ument yourname *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 2/180

 * Prints "Hi, Bo). Ho are you4" ere "Bo)" is replaced )y te * command5line ar#ument. * * $ java 2se3r#ument Bo) * Hi, Bo). Ho are you4 * * $ java 2se3r#ument 3lice * Hi, 3lice. Ho are you4 *  *************************************************************************/

pu)lic class 2se3r#ument +

  pu)lic static void main-trin# ar#s0 +  -ystem.out.print"Hi, "0(  -ystem.out.printar#s60(  -ystem.out.println". Ho are you4"0(  1

1

TenHelloWorlds.java

Below is the syntax highlighted version of TenHelloWorlds.java from §1.1 Hello World.

/*************************************************************************

 * Compilation: javac %enHelloWorlds.java * Execution: java %enHelloWorlds * * Prints "Hello, World" ten times. 7ou!ll learn a)out a more * compact ay to do tis in -ection &.8 en e introduce loops. * * $ java %enHelloWorlds * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World * Hello, World *  *************************************************************************/

pu)lic class %enHelloWorlds +

  pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 3/180

  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  -ystem.out.println"Hello, World"0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri $ec 1% 1&"2%"'0 (S) 2010.

Hi.java

Below is the syntax highlighted version of Hi.java from §1.1 Hello World.

/************************************************************************* * Compilation: javac Hi.java * Execution: java Hi yourname *

 * Prints "Hi, Bo). Ho are you4" ere "Bo)" is replaced )y te * command5line parameter. * * $ java Hi Bo) * Hi, Bo). Ho are you4 * * $ java Hi 3lice * Hi, 3lice. Ho are you4 *  *************************************************************************/

pu)lic class Hi +

  pu)lic static void main-trin# ar#s0 +  -ystem.out.print"Hi, "0(  -ystem.out.printar#s60(  -ystem.out.println". Ho are you4"0(  1

1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 4/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri $ec 1% 1&"2%"'0 (S) 2010.

UseThree.java

Below is the syntax highlighted version of UseThree.java from §1.1 Hello World.

/************************************************************************* * Compilation: javac 2se%ree.java * Execution: java 2se%ree name& name9 name8 * * %aes 8 command5line ar#uments and prints tem in reverse order * in a riendly #reetin#. * * $ java 2se%ree 3lice Bo) Carol * Hi, Carol, Bo), and 3lice. * * $ java 2se%ree Carol Bo) 3lice * Hi, 3lice, Bo), and Carol. *  *************************************************************************/

pu)lic class 2se%ree +

  pu)lic static void main-trin# ar#s0 +

  -ystem.out.print"Hi, "0(  -ystem.out.printar#s90(  -ystem.out.print", "0(  -ystem.out.printar#s&0(  -ystem.out.print", and "0(  -ystem.out.printar#s60(  -ystem.out.println"."0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri $ec 1% 1&"2%"'0 (S) 2010.Initials.java

Below is the syntax highlighted version of Initials.java from §1.1 Hello World.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 5/180

/************************************************************************* * Compilation: javac ;nitials.java * Execution: java ;nitials * * Prints te initials < = W. *  *************************************************************************/

pu)lic class ;nitials +

  pu)lic static void main-trin# ar#s0 +  -ystem.out.println"** *** ********** ** ***"0(  -ystem.out.println"** *** ** ** ** ***** "0(  -ystem.out.println"** *** ** ** ** **** ** "0(  -ystem.out.println"** *** ** ** ** **** ** "0(  -ystem.out.println"***** ** ** ** **

** ** "0(  -ystem.out.println"** *** ** ** ** **** ** "0(  -ystem.out.println"** *** ** ** ** **** ** "0(  -ystem.out.println"** *** ** ** ****** "0(  -ystem.out.println"** *** ********** ** "0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri $ec 1% 1&"2%"'0 (S) 2010.

1.2 Built-in Types of Data

Ruler.java

Below is the syntax highlighted version of uler.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac >uler.java * Execution: java >uler ** Prints te relative len#ts o te su)divisions on a ruler. ** $ java >uler * &

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 6/180

 * & 9 &* & 9 & 8 & 9 &* & 9 & 8 & 9 & ? & 9 & 8 & 9 &* & 9 & 8 & 9 & ? & 9 & 8 & 9 & @ & 9 & 8 & 9 & ? & 9 & 8 & 9 &*  *************************************************************************/

pu)lic class >uler +pu)lic static void main-trin# ar#s0 +

-trin# ruler& A " & "(  -trin# ruler9 A ruler& "9" ruler&(  -trin# ruler8 A ruler9 "8" ruler9(  -trin# ruler? A ruler8 "?" ruler8(  -trin# ruler@ A ruler? "@" ruler?(

  -ystem.out.printlnruler&0(  -ystem.out.printlnruler90(  -ystem.out.printlnruler80(  -ystem.out.printlnruler?0(  -ystem.out.printlnruler@0(

  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )!e *ov 1' 1+"2%"'0 (S) 2011.

Intps.java

Below is the syntax highlighted version of Int%#s.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac ;ntps.java * Execution: java ;ntps a ) ** ;llustrates te inte#er operations a * ), a / ), and a $ ). * * $ java ;ntps &98? DD * &98? DD A &888 * &98? * DD A &99& * &98? / DD A &9 * &98? $ DD A ? * &98? A &9 * DD ? ** $ java ;ntps &6 58 * &6 58 A ' * &6 * 58 A 586 * &6 / 58 A 58 * &6 $ 58 A & * &6 A 58 * 58 &

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 7/180

 *  *************************************************************************/

pu)lic class ;ntps +

pu)lic static void main-trin# ar#s0 +  int a A ;nte#er.parse;ntar#s60(  int ) A ;nte#er.parse;ntar#s&0(  int sum A a )(  int prod A a * )(  int Fuot A a / )(  int rem A a $ )(

  -ystem.out.printlna " " ) " A " sum0(  -ystem.out.printlna " * " ) " A " prod0(  -ystem.out.printlna " / " ) " A " Fuot0(  -ystem.out.printlna " $ " ) " A " rem0(  -ystem.out.printlna " A " Fuot " * " ) " " rem0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" on -an 1 1"10"1 (S) 2011.

Dou!leps.java

Below is the syntax highlighted version of $ou&le%#s.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac =ou)leps.java * Execution: java =ou)leps a ) ** ;llustrates te inte#er operations a ), a * ), and a / ). * * $ java =ou)leps &98? DD * &98?.6 DD.6 A &888.6 * &98?.6 * DD.6 A &99&.6 * &98?.6 / DD.6 A &9.???????@ * &98?.6 $ DD.6 A ?.6 * * $ java =ou)leps &6 58 * &6.6 58.6 A '.6 * &6.6 * 58.6 A 586.6 * &6.6 / 58.6 A 58.888888888888888@ * &6.6 $ 58.6 A &.6 ** $ java =ou)leps ;ninity 8 * ;ninity 8.6 A ;ninity * ;ninity * 8.6 A ;ninity * ;ninity / 8.6 A ;ninity

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 8/180

 * ;ninity $ 8.6 A GaG *  *************************************************************************/

pu)lic class =ou)leps +

pu)lic static void main-trin# ar#s0 +  dou)le a A =ou)le.parse=ou)lear#s60(  dou)le ) A =ou)le.parse=ou)lear#s&0(  dou)le sum A a )(  dou)le prod A a * )(  dou)le Fuot A a / )(  dou)le rem A a $ )(

  -ystem.out.printlna " " ) " A " sum0(  -ystem.out.printlna " * " ) " A " prod0(  -ystem.out.printlna " / " ) " A " Fuot0(  -ystem.out.printlna " $ " ) " A " rem0(

  -ystem.out.println0(

  -ystem.out.println"sinpi/90 A " at.sinat.P;/900(  -ystem.out.println"lo#e0 A " at.lo#at.E00(

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

"ua#rati$.java

Below is the syntax highlighted version of 'uadrati(.java from §1.! Built"in Ty#es of $ata. 

/************************************************************************* * Compilation: javac Iuadratic.java * Execution: java Iuadatic ) c ** Jiven ) and c, solves or te roots o x*x )*x c. * 3ssumes )ot roots are real valued. * * $ java Iuadratic 58.6 9.6 * 9.6 * &.6 * * $ java Iuadratic 5&.6 5&.6 * &.&K688DKK'?DKD@ * 56.&K688DKK'?DKD?D * * >emar: &.&K688D... is te #olden ratio. * * $ java Iuadratic &.6 &.6

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 9/180

 * GaG * GaG * *  *************************************************************************/

pu)lic class Iuadratic +

pu)lic static void main-trin# ar#s0 +dou)le ) A =ou)le.parse=ou)lear#s60(

  dou)le c A =ou)le.parse=ou)lear#s&0(

  dou)le discriminant A )*) 5 ?.6*c(  dou)le sFroot A at.sFrtdiscriminant0(

  dou)le root& A 5) sFroot0 / 9.6(  dou)le root9 A 5) 5 sFroot0 / 9.6(

  -ystem.out.printlnroot&0(  -ystem.out.printlnroot90(

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

 Trig.java

Below is the syntax highlighted version of Trig.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac %ri#.java * Execution: java %ri# an#le ** ;llustrates various tri# operations. >eads in an an#le in de#rees0, * converts to radians, and perorms various tri#onometric* calculations. * * $ java %ri# * sin86.60 A 6.?DDDDDDDDDDDDDDD? * cos86.60 A 6.K69@?68'K??8K' * tan86.60 A 6.@''8@69D&KD9@' * 6.?DDDDDDDDDDDDDDD? / 6.K69@?68'K??8K' A 6.@''8@69D&KD9@ * 6.9?DDDDDDDDDDDDDD? 6.'@6666666666666& A &.6 *  *************************************************************************/

pu)lic class %ri# +pu)lic static void main-trin# ar#s0 +

  dou)le de#rees A =ou)le.parse=ou)lear#s60(  dou)le radians A at.to>adiansde#rees0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 10/180

  dou)le s A at.sinradians0(  -ystem.out.println"sin" de#rees "0 A " s0(

  dou)le c A at.cosradians0(  -ystem.out.println"cos" de#rees "0 A " c0(

  dou)le t A at.tanradians0(  -ystem.out.println"tan" de#rees "0 A " t0(  -ystem.out.printlns " / " c " A " s / c0(

  dou)le r A s*s c*c(  -ystem.out.printlns*s " " c*c " A " r0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

%eap&ear.java

Below is the syntax highlighted version of )ea#*ear.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac Leap7ear.java * Execution: java Leap7ear G *

* Prints true i G corresponds to a leap year, and alse oterise. * 3ssumes G MA &@K9, correspondin# to a year in te Jre#orian calendar. * * $ java Leap7ear 966? * true * * $ java Leap7ear &D66 * alse * * $ java Leap7ear 9666 * true *  *************************************************************************/

pu)lic class Leap7ear +pu)lic static void main-trin# ar#s0 +

int year A ;nte#er.parse;ntar#s60(  )oolean isLeap7ear(

  // divisi)le )y ?  isLeap7ear A year $ ? AA 60(

  // divisi)le )y ? and not &66

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 11/180

  isLeap7ear A isLeap7ear NN year $ &66 OA 60(

  // divisi)le )y ? and not &66 unless divisi)le )y ?66  isLeap7ear A isLeap7ear year $ ?66 AA 60(

  -ystem.out.printlnisLeap7ear0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

Ran#omInt.java

Below is the syntax highlighted version of andomInt.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac >andom;nt.java * Execution: java >andom;nt G ** Prints a pseudo5random inte#er )eteen 6 and G5&. * ;llustrate an explicit type conversion cast0 rom dou)le to int. * * $ java >andom;nt  * 7our random inte#er is: @ * * $ java >andom;nt

 * 7our random inte#er is: 6 * * $ java >andom;nt &666 * 7our random inte#er is: &9D * * $ java >andom;nt &666 * 7our random inte#er is: 888 *  *************************************************************************/

pu)lic class >andom;nt +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  // a pseudo5random real )eteen 6.6 and &.6  dou)le r A at.random0(

// a pseudo5random inte#er )eteen 6 and G5&  int n A int0 r * G0(

  -ystem.out.println"7our random inte#er is: " n0(  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 12/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

Appen#i' A( perator )re$e#en$e in *ava

+ava has well"defined rules for s#e(ifying the order in whi(h the o#erators in an ex#ression are

evaluated when the ex#ression has several o#erators. ,or exam#le- multi#li(ation and division

have a higher #re(eden(e than addition and su&tra(tion. re(eden(e rules (an &e overridden &y

ex#li(it #arentheses.

Precedence Order.+hen t,o operators share an operan# the operator ,ith the higher  precedence 

goes rst. or e'ample/ 1 0 2 is treate# as 1 0 32 4/ ,hereas 1 2 0 is

treate# as 31 24 0 sin$e multipli$ation has a higher pre$e#en$e than a##ition.

Associativity.+hen t,o operators ,ith the same pre$e#en$e the e'pression is evaluate#

a$$or#ing to its associativity . or e'ample x A y A Q A &' is treate# as x A y A Q

A &'00/ leaving all three varia!les ,ith the value 15/ sin$e the A operator has right-

to-left asso$iativity 3an# an assignment statement evaluates to the value on the

right han# si#e4. n the other han#/ '9 / 9 / 8 is treate# as '9 / 90 / 8 sin$e the

/ operator has left-to-right asso$iativity.

Precedence and associativity of Java operators.

 The ta!le !elo, sho,s all *ava operators from highest to lo,est pre$e#en$e/ along,ith their asso$iativity. 6ost programmers #o not memori7e them all/ an# even

those that #o still use parentheses for $larity.

Operator Description Level Associativity

.

0

55 

a$$ess array element

a$$ess o!je$t mem!er

invo8e a metho#

post-in$rement

post-#e$rement

1 left to right

55

5

pre-in$rement

pre-#e$rement

unary plus

unary minus

2 right to left

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 13/180

O

R logi$al 9T

!it,ise 9T

0

ne $ast

o!je$t $reation right to left

*

/

$ multipli$ative : left to right

5

 a##itive

string $on$atenation; left to right

SS MM

MMM shift < left to right

S SAM MA

instanceo 

relational

type $omparison5 left to right

AA

OA e=uality > left to right

N !it,ise A9D ? left to right

T !it,ise @R 1 left to right

!it,ise R 11 left to right

NN $on#itional A9D 12 left to right

$on#itional R 1 left to right

4: $on#itional 1: right to left

  A A 5A *A /A $A

 NA TA ASSA MMA MMMA

assignment 1; right to left

Caveats. There is no e'pli$it operator pre$e#en$e ta!le in the *ava %anguage pe$i$ation

an# #iCerent ta!les on the +e! an# in te't!oo8s #isagree in some minor ,ays.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 14/180

Order of evaluation.In *ava/ the left operan# is al,ays evaluate# !efore the right operan#. Also applies

to fun$tion arguments.

Short circ!iting . When using the (onditional A/$ and % o#erators 0NN and - +ava does not

evaluate the se(ond o#erand unless it is ne(essary to resolve the result. Allows statements li2e is OA null NN s.len#t0 S &60 to wor2 relia&ly. rogrammers rarely use the non short"

(ir(uiting versions 0N and with )oolean ex#ressions.

Precedence order gone awry.ometimes the pre$e#en$e or#er #ene# in a language #o not $onform ,ith

mathemati$al norms. or e'ample/ in 6i$rosoft '$el/ -aE! is interprete# as 3-a4E!

instea# of -3aE!4. o -1E2 is e=ual to 1 instea# of -1/ ,hi$h is the values most

mathemati$ians ,oul# e'pe$t. 6i$rosoft a$8no,le#ges this =uir8 as a F#esign

$hoi$eF. ne ,on#ers ,hether the programmer ,as relying on the G pre$e#en$e

or#er in ,hi$h unary operators have higher pre$e#en$e than !inary operators. Thisrule agrees ,ith mathemati$al $onventions for all G operators/ !ut fails ,ith the

a##ition of the e'ponentiation operator. n$e the or#er ,as esta!lishe# in 6i$rosoft

'$el 2./ it $oul# not easily !e $hange# ,ithout !rea8ing !a$8,ar# $ompati!ility.

Exercises.

1. +hat is the result of the follo,ing $o#e fragment

int x A @(int y A &6(int Q A x * y55(

2. +hat is the result of the follo,ing $o#e fragment 'plain.

-ystem.out.println"& 9 A " & 90(-ystem.out.println"& 9 A " & 900(

 Answer ( & 9 A &9 an# & 9 A 8/ respe$tively. If either 3or !oth4 of the

operan#s of the  operator is a string/ the other is automati$ally $ast to a

string. tring $on$atenation an# a##ition have the same pre$e#en$e. in$e

they are left-asso$iative/ the operators are evaluate# left-to-right. The

parentheses in the se$on# statement ensures that the se$on#  operator

performs a##ition instea# of string $on$atenation.

. A## parentheses to the follo,ing e'pression to ma8e the or#er of evaluationmore $lear.

year $ ? AA 6 NN year $ &66 OA 6 year $ ?66 AA 6

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 15/180

 Answer ( %eap&ear.java sho,s a variety of e=uivalent e'pressions/ in$lu#ing

the follo,ing reasona!le alternative.

year $ ? AA 60 NN year $ &66 OA 600 year $ ?66 AA 60

:. +hat #oes the follo,ing $o#e fragment print

-ystem.out.println& 9 "a)c"0(-ystem.out.println"a)c" & 90(

 /nwer 3 8a)c and a)c&9- res#e(tively. The 4 o#erator is left asso(iative- whether it is

string (on(atenation or arithmeti( #lus.

 Lat odiied on /pri 10, 201.

5o#yright 6 !77!8!71! o&ert 9edgewi(2  and :evin Wayne. All rights reserved.

umfT,oDi$e.java

Below is the syntax highlighted version of 9um%fTwo$i(e.java from §1.! Built"in Ty#es of

$ata.

/************************************************************************* * Compilation: javac -um%o=ice.java * Execution: java -um%o=ice ** Jenerate 9 inte#ers )eteen & and , and print teir sum. ** $ java -um%o=ice * @ * * $ java -um%o=ice * D * * $ java -um%o=ice

 * 8 * * $ java -um%o=ice * && * * $ java -um%o=ice * K * * $ java -um%o=ice * '

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 16/180

 *  *************************************************************************/

pu)lic class -um%o=ice +pu)lic static void main-trin# ar#s0 +

  int -;=E- A (  int a A & int0 at.random0 * -;=E-0(  int ) A & int0 at.random0 * -;=E-0(  int sum A a )(  -ystem.out.printlnsum0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

pringeason.java

Below is the syntax highlighted version of 9#ring9eason.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac -prin#-eason.java * Execution: java day mont ** Prints true i te #iven day and mont all )eteen arc 96 inclusive0 * and Uune 96 inclusive0. ** $ java -prin#-eason 8 96

 * true * * $ java -prin#-eason 96 * true * * $ java -prin#-eason ? &@ * true * * $ java -prin#-eason D && * alse *  *************************************************************************/

pu)lic class -prin#-eason +pu)lic static void main-trin# ar#s0 +

int mont A ;nte#er.parse;ntar#s60(  int day A ;nte#er.parse;ntar#s&0(  )oolean is-prin# A mont AA 8 NN day MA 96 NN day SA 8&0  mont AA ? NN day MA & NN day SA 860  mont AA @ NN day MA & NN day SA 8&0  mont AA NN day MA & NN day SA 960(

  -ystem.out.printlnis-prin#0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 17/180

  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri /!g ' 0&"+3" ($) 2011.

+in#Ghill.java

Below is the syntax highlighted version of Wind5hill.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac WindCill.java * Execution: java WindCill t v * * Jiven te temperature t in Vareneit0 and te ind speed v * in miles per our0, compute te ind cill usin# te ormula * rom te Gational Weater -ervice * * A 8@.'? 6.9&@*t 6.?9'@*t 5 8@.'@0 * v T 6.& * * >eerence: ttp://.ns.noaa.#ov/om/indcill/index.stml *  *************************************************************************/

pu)lic class WindCill +  pu)lic static void main-trin# ar#s0 +  dou)le t A =ou)le.parse=ou)lear#s60(

  dou)le v A =ou)le.parse=ou)lear#s&0(  dou)le A 8@.'? 6.9&@*t 6.?9'@*t 5 8@.'@0 * at.pov, 6.&0(  -ystem.out.println"%emperature A " t0(  -ystem.out.println"Wind speed A " v0(  -ystem.out.println"Wind cill A " 0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

GartesianTo)olar.java

Below is the syntax highlighted version of 5artesianToolar.java from §1.! Built"in Ty#es of

$ata.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 18/180

/************************************************************************* * Compilation: javac Cartesian%oPolar.java * Execution: java Cartesian%oPolar x y ** >ead in Cartesian coordinates x, y0 and print out polar coordinates * r, teta0. * * $ java Cartesian%oPolar 8.6 ?.6 * r A @.6 * teta A 6.D9'9D@9&K66&&99 *  *************************************************************************/

pu)lic class Cartesian%oPolar +pu)lic static void main-trin# ar#s0 +

dou)le x A =ou)le.parse=ou)lear#s60(  dou)le y A =ou)le.parse=ou)lear#s&0( 

dou)le r A at.sFrtx*x y*y0(  dou)le teta A at.atan9y, x0(

  -ystem.out.println"r A " r0(  -ystem.out.println"teta A " teta0(  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri /!g ' 0&"'0"1 ($) 2011.

Dayf+ee8.java

Below is the syntax highlighted version of $ay%fWee2.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac =ayWee.java * Execution: java =ayWee m d y * * >ead in te mont m0, day d0, and year y0 and print out at * day o te ee it alls on accordin# to te Jre#orian calendar. * Vor use & or Uanuary, 9 or Ve)ruary, and so ort. utputs * 6 or -unday, & or onday, and so ort. * * y6 A y 5 &? 5 m0 / &9 * x A y6 y6/? 5 y6/&66 y6/?66 * m6 A m &9 * &? 5 m0 / &90 5 9 * d A d x 8&*m60/&90 mod ' * * * $ java =ayWee K 9 &D@8 // 3u#ust 9, &D@8 * 6 // -unday

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 19/180

 * * $ java =ayWee & & 9666 // Uanuary &, 9666 * // -aturday *  *************************************************************************/

pu)lic class =ayWee +  pu)lic static void main-trin# ar#s0 +

int m A ;nte#er.parse;ntar#s60(  int d A ;nte#er.parse;ntar#s&0(  int y A ;nte#er.parse;ntar#s90(

  int y6 A y 5 &? 5 m0 / &9(  int x A y6 y6/? 5 y6/&66 y6/?66(  int m6 A m &9 * &? 5 m0 / &90 5 9(  int d6 A d x 8&*m60/&90 $ '(

  -ystem.out.printlnd60(  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri /!g ' 0&"+&"14 ($) 2011.

tats;.java

Below is the syntax highlighted version of 9tats;.java from §1.! Built"in Ty#es of $ata. 

/************************************************************************* * Compilation: javac [email protected] * Execution: java -tats@ ** Jenerate and print @ random values )eteen 6.6 and &.6, and print * teir avera#e value, min value, and max value. * * $ java -tats@ * * 6.'968@8'9'D&&'K?& * 6.6D@'??8@&@''8K??K * 6.KD'D'?&D898&K * 6.&&D?D689&K?8@@&&8 * 6.98?9@@&D@?@8D'@?? * 3vera#e A 6.?&8@8@@899&D'8 * in A 6.6D@'??8@&@''8K??K * ax A 6.KD'D'?&D898&K * * $ java -tats@ * 6.9@@98K9&''8@@?&8? * 6.@''&8&D89?9?DK' * 6.&?&'6998@88D?&DK?

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 20/180

 * 6.9@8???KD@99& * 6.KD@8'?D@'9&'DD * 3vera#e A 6.??86'?&K6D'8K?9? * in A 6.&?&'6998@88D?&DK? * ax A 6.KD@8'?D@'9&'DD *  *************************************************************************/

pu)lic class -tats@ +pu)lic static void main-trin# ar#s0 +

int G A @(  dou)le x& A at.random0(  dou)le x9 A at.random0(  dou)le x8 A at.random0(  dou)le x? A at.random0(  dou)le x@ A at.random0(

  // print @ values  -ystem.out.printlnx&0(  -ystem.out.printlnx90(

  -ystem.out.printlnx80(  -ystem.out.printlnx?0(  -ystem.out.printlnx@0(

  // compute stats  dou)le min A at.minx&, at.minx9, at.minx8, at.minx?,x@0000(  dou)le max A at.maxx&, at.maxx9, at.maxx8, at.maxx?,x@0000(  dou)le avera#e A x& x9 x8 x? x@0 / G(

  // print stats  -ystem.out.println"3vera#e A " avera#e0(  -ystem.out.println"in A " min0(  -ystem.out.println"ax A " max0(  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri /!g ' 0&"+3" ($) 2011.

 Threeort.java

Below is the syntax highlighted version of Three9ort.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac %ree-ort.java * Execution: java %ree-ort a ) c ** >ead 8 inte#er values rom te command line and print tem

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 21/180

 * in ascendin# order. * * $ java %ree-ort &' @6 88 * &' * 88 * @6 * * $ java %ree-ort @6 88 &' * &' * 88 * @6 * * $ java %ree-ort &' @6 &' * &' * &' * @6 *  *************************************************************************/

pu)lic class %ree-ort +

pu)lic static void main-trin# ar#s0 +int a A ;nte#er.parse;ntar#s60(

  int ) A ;nte#er.parse;ntar#s&0(  int c A ;nte#er.parse;ntar#s90(

  // compute stats  int min A at.mina, at.min), c00(  int max A at.maxa, at.max), c00(  int median A a ) c 5 min 5 max(

  // print stats  -ystem.out.printlnmin0(  -ystem.out.printlnmedian0(  -ystem.out.printlnmax0(  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri -an 2% 0+"2"10 (S) 2012.

Dragon.java

Below is the syntax highlighted version of $ragon.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac =ra#on.java * Execution: java =ra#on ** Prints te instructions or drain# a dra#on curve o orders 6 * trou# @.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 22/180

 ** $ java =ra#on * V * VLV * VLVLV>V * VLVLV>VLVLV>V>V * VLVLV>VLVLV>V>VLVLVLV>V>VLV>V>V * VLVLV>VLVLV>V>VLVLVLV>V>VLV>V>VLVLVLV>VLVLV>V>V>VLVLV>V>VLV>V>V *  *************************************************************************/

pu)lic class =ra#on +pu)lic static void main-trin# ar#s0 +

-trin# dra#on6 A "V"(  -trin# no#ard6 A "V"(  -trin# dra#on& A dra#on6 "L" no#ard6(  -trin# no#ard& A dra#on6 ">" no#ard6(  -trin# dra#on9 A dra#on& "L" no#ard&(  -trin# no#ard9 A dra#on& ">" no#ard&(  -trin# dra#on8 A dra#on9 "L" no#ard9(

  -trin# no#ard8 A dra#on9 ">" no#ard9(  -trin# dra#on? A dra#on8 "L" no#ard8(  -trin# no#ard? A dra#on8 ">" no#ard8(  -trin# dra#on@ A dra#on? "L" no#ard?(

  -ystem.out.printlndra#on60(  -ystem.out.printlndra#on&0(  -ystem.out.printlndra#on90(  -ystem.out.printlndra#on80(  -ystem.out.printlndra#on?0(  -ystem.out.printlndra#on@0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" on -an 1 1"10"1 (S) 2011.

Distan$e.java

Below is the syntax highlighted version of $istan(e.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac =istance.java * Execution: java =istance x y ** Print te distance rom x, y0 to te ori#in, ere x and y * are inte#ers. ** $ java =istance 8 ? * distance rom 8, ?0 to 6, 60 A @.6

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 23/180

 * * $ java =istance @ &9 * distance rom @, &90 to 6, 60 A &8.6 * * $ java =istance 9 & * distance rom 9, &0 to 6, 60 A 9.986'D''?DD'D *  *************************************************************************/

pu)lic class =istance +  pu)lic static void main-trin# ar#s0 +

  // parse x5 and y5coordinates rom command5line ar#uments  int x A ;nte#er.parse;ntar#s60(  int y A ;nte#er.parse;ntar#s&0(

  // compute distance to 6, 60  dou)le dist A at.sFrtx*x y*y0( 

// output distance

  -ystem.out.println"distance rom " x ", " y "0 to 6, 60 A " dist0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

,ap.java

Below is the syntax highlighted version of 9wa#.java from §1.! Built"in Ty#es of $ata.

/************************************************************************* * Compilation: javac -ap.java * Execution: java -ap a ) * * >ead in to inte#er command5line ar#uments a and ) and * sap teir values usin# te sappin# idiom descri)ed on p. &'. * 3ter eac assi#nment statement, use -ystem.out.println0 to * print out a trace o te varia)les. * * $ java -ap && DD * a A &&, ) A DD, c A 6 * a A &&, ) A DD, c A && * a A DD, ) A DD, c A && * a A DD, ) A &&, c A && *  *************************************************************************/

pu)lic class -ap +  pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 24/180

  int a A ;nte#er.parse;ntar#s60(  int ) A ;nte#er.parse;ntar#s&0(  int c A 6(

  -ystem.out.println"a A " a ", ) A " ) ", c A " c0(c A a(

  -ystem.out.println"a A " a ", ) A " ) ", c A " c0(a A )(

  -ystem.out.println"a A " a ", ) A " ) ", c A " c0() A c(

  -ystem.out.println"a A " a ", ) A " ) ", c A " c0(1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

Divisi!ility.java

Below is the syntax highlighted version of $ivisi&ility.java from §1.! Built"in Ty#es of $ata.

Divisi!ility.java

Below is the syntax highlighted version of $ivisi&ility.java from §1.! Built"in Ty#es of $ata.

/*************************************************************************

 * Compilation: javac Divisibility.java

 * Execution: java Divisibility X Y 

 *

* Reads in two command line inputs X and Y and prints true i! bot"

 * are divisible by #$ and !alse ot"erwise.

 *

 * % java Divisibility &' (&

 * true

 * * % java Divisibility ' (&

 * !alse

 *

* % java Divisibility &)) ())

 * !alse

 *

 * a % # is t"e remainder w"en you divide # into a. ! t"e remainder 

 * is )$ t"en a is divisible by #.

 *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 25/180

  *************************************************************************/ 

pu)lic class =ivisi)ility +  pu)lic static void  main-trin# ar#s0 +  int  A ;nte#er. parseIntar#s60(  int 7 A ;nte#er. parseIntar#s&0( 

)oolean is=ivisi)le A  $ ' AA 60 NN 7 $ ' AA 60(

  -ystem.out. printlnis=ivisi)le0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" #ri ar 2 0&"3"+0 ($) 2012.

Gar%oan.java

Below is the syntax highlighted version of 5ar)oan.java from §1.! Built"in Ty#es of $ata.

/*************************************************************************

 * Compilation: javac CarLoan.java * Execution: java CarLoan P 7 > * * Calculate te montly payments i you tae out a XP loan or * 7 years it annual interest rate > $, ere interested is * compounded montly. * * P r * payment A 55555555555555555 ere n A &9 * 7, r A > / &9 / &66 * & 5 & r0T5n0 * * * $ java CarLoan 96666 @  * ontly payments A 8K.@686@KK@@@

 * %otal interest A 8&DD.8&K8@8&8D89 * * * Bu#s * 5555 * =oes not or i > A 6$ interest. Easy to ix i you no a)out * i5else statements. *  *************************************************************************/

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 26/180

pu)lic class CarLoan +  pu)lic static void main-trin# ar#s0 +  dou)le P A =ou)le.parse=ou)lear#s60(  dou)le 7 A =ou)le.parse=ou)lear#s&0(  dou)le > A =ou)le.parse=ou)lear#s90(

  dou)le r A > / &9 / &66( // montly interest rate  dou)le n A &9 * 7( // num)er o monts

  dou)le payment A P * r0 / & 5 at.po&r, 5n00(  dou)le interest A payment * n 5 P(

  -ystem.out.println"ontly payments A " payment0(  -ystem.out.println"%otal interest A " interest0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" on -an 1 1"10"1 (S) 2011.

1. Gon#itionals an# %oops

lip.java

Below is the syntax highlighted version of ,li#.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Vlip.java * Execution: java Vlip ** -imulate a air coin lip and print out "Heads" or "%ails" accordin#ly. * * $ java Vlip * Heads * * $ java Vlip * Heads * * $ java Vlip

 * %ails * *  *************************************************************************/

pu)lic class Vlip +

  pu)lic static void main-trin# ar#s0 +// at.random0 returns a value )eteen 6.6 and &.6

  // so it it eads or tails @6$ o te time

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 27/180

  i at.random0 S 6.@0 -ystem.out.println"Heads"0(  else -ystem.out.println"%ails"0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

 TenHellos.java

Below is the syntax highlighted version of TenHellos.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac %enHellos.java * Execution: java %enHellos ** Prints it Hello or i A & to &6. ;lllustrates usin# a ile loop * or a repetitive tas. * * $ java %enHellos * &st Hello * 9nd Hello* 8rd Hello * ?t Hello * @t Hello * t Hello * 't Hello * Kt Hello

 * Dt Hello * &6t Hello *  *************************************************************************/

pu)lic class %enHellos +pu)lic static void main-trin# ar#s0 +

  // print out special cases ose ordinal doesn!t end in t  -ystem.out.println"&st Hello"0(  -ystem.out.println"9nd Hello"0(  -ystem.out.println"8rd Hello"0(

  // count rom i A ? to &6  int i A ?(  ile i SA &60 +  -ystem.out.printlni "t Hello"0(  i A i &(  1

  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 28/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

)o,ersfT,o.java

Below is the syntax highlighted version of owers%fTwo.java from §1.< 5onditionals and

)oo#s.

/************************************************************************* * Compilation: javac Poers%o.java * Execution: java Poers%o G ** %is pro#ram taes a command5line ar#ument G and prnts a ta)le o * te poers o 9 tat are less tan or eFual to 9TG. * * $ java Poers%o @

 * 6 & * & 9 * 9 ? * 8 K * ? & * @ 89 * * $ java Poers%o  * 6 & * & 9 * 9 ? * 8 K * ? &

 * @ 89 * ? * * >emars * 555555555555 * nly ors i 6 SA G S 8& since 9T8& overlos an int. *  *************************************************************************/

pu)lic class Poers%o +  pu)lic static void main-trin# ar#s0 +

  // read in one command5line ar#ument  int G A ;nte#er.parse;ntar#s60(

  int i A 6( // count rom 6 to G5&  int poer%o A &( // te it poer o to

  // repeat until i eFuals G  ile i SA G0 +  -ystem.out.printlni " " poer%o0( // print out te poero to

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 29/180

  poer%o A 9 * poer%o( // dou)le to #et tenext one  i A i &(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Harmoni$.java

Below is the syntax highlighted version of Harmoni(.java from §1.< 5onditionals and )oo#s. 

/************************************************************************* * Compilation: javac Harmonic.java * Execution: java Harmonic G ** Prints te Gt armonic num)er: &/& &/9 ... &/G. ** $ java Harmonic &6 * 9.D9KDK9@8DK9@8K * * $ java Harmonic &6666

 * D.'K'6686??8?K *  *************************************************************************/

pu)lic class Harmonic +pu)lic static void main-trin# ar#s0 +

// command5line ar#ument  int G A ;nte#er.parse;ntar#s60(

  // compute &/& &/9 &/8 ... &/G  dou)le sum A 6.6(  or int i A &( i SA G( i0 +

  sum A &.6 / i(  1

  // print out Gt armonic num)er  -ystem.out.printlnsum0(  1

1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 30/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

=rt.java

Below is the syntax highlighted version of 9=rt.java from §1.< 5onditionals and )oo#s. 

/************************************************************************* * Compilation: javac -Frt.java * Execution: java -Frt c ** Computes te sFuare root o a nonne#ative num)er c usin# * Geton!s metod: * 5 initialiQe t A c * 5 replace t it te avera#e o c/t and t

 * 5 repeat until desired accuracy reaced ** $ java -Frt 9 * &.?&?9&8@98'86D@ * * $ java -Frt &666666 * &666.6 * * $ java -Frt 6.? * 6.89?@@@89688'@D * * $ java -Frt &6?K@'@ * &698.DDD@&&'&K88 ** $ java -Frt &???? * ?6K9.9&6'@69&868 * * $ java -Frt 6 * 6.6 ** $ java -Frt &e5@6 * D.DDDDDDDDDDDDDDDE59 * * * >emars * 5555555555 * 5 usin# at.a)s0 is reFuired i c S &

 * * * <non )u#s * 5555555555 * 5 #oes into an ininite loop i te input is ne#ative *  *************************************************************************/

pu)lic class -Frt +pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 31/180

  // read in te command5line ar#ument  dou)le c A =ou)le.parse=ou)lear#s60(  dou)le epsilon A &e5&@( // relative error tolerance  dou)le t A c( // estimate o te sFuare root o c

  // repeatedly apply Geton update step until desired precision isacieved  ile at.a)st 5 c/t0 M epsilon*t0 +  t A c/t t0 / 9.6(  1

  // print out te estimate o te sFuare root o c  -ystem.out.printlnt0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Binary.java

Below is the syntax highlighted version of Binary.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Binary.java

 * Execution: java Binary n ** Prints out n in )inary. ** $ java Binary @ * &6& * * $ java Binary &6 * &&6&6&6 * * $ java Binary 6 * 6 ** $ java Binary & * &6666 * * Limitations * 55555555555 * =oes not andle ne#ative inte#ers. * * >emars * 5555555 * could use ;nte#er.toBinary-trin#G0 instead.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 32/180

 *  *************************************************************************/

pu)lic class Binary +pu)lic static void main-trin# ar#s0 +

// read in te command5line ar#ument  int n A ;nte#er.parse;ntar#s60(

  // set v to te lar#est poer o to tat is SA n  int v A &(  ile v SA n/90 +  v A v * 9(  1 

// cec or presence o poers o 9 in n, rom lar#est to smallest  ile v M 60 +

  // v is not present in ni n S v0 +

  -ystem.out.print60(  1

  // v is present in n, so remove v rom n  else +  -ystem.out.print&0(  n A n 5 v(  1

  // next smallest poer o 9  v A v / 9(  1

  -ystem.out.println0(

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

am!ler.java

Below is the syntax highlighted version of >am&ler.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Jam)ler.java * Execution: java Jam)ler stae #oal G ** -imulates a #am)ler o start it Xstae and place air X& )ets

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 33/180

 * until se #oes )roe or reac X#oal. <eeps trac o te num)er o * times se ins and te num)er o )ets se maes. >un te experiment G * times, avera#es te results, and prints tem out. * * $ java Jam)ler @6 9@6 &666 * Percent o #ames on A &D.6 * 3v# Y )ets A D'.869 * * $ java Jam)ler @6 &@6 &666 * Percent o #ames on A 8&.D * 3v# Y )ets A ?D&9.&8 * * $ java Jam)ler @6 &66 &666 * Percent o #ames on A ?D. * 3v# Y )ets A [email protected]@9 *  *************************************************************************/

pu)lic class Jam)ler +

pu)lic static void main-trin# ar#s0 +  int stae A ;nte#er.parse;ntar#s60( // #am)ler!s statin#)anroll  int #oal A ;nte#er.parse;ntar#s&0( // #am)ler!s desired)anroll  int % A ;nte#er.parse;ntar#s90( // num)er o trials toperorm

  int )ets A 6( // total num)er o )ets made  int ins A 6( // total num)er o #ames on

  // repeat G times  or int t A 6( t S %( t0 +

  // do one #am)ler!s ruin simulation  int cas A stae(  ile cas M 6 NN cas S #oal0 +  )ets(  i at.random0 S 6.@0 cas( // in X&  else cas55( // lose X&  1  i cas AA #oal0 ins( // did #am)ler #o acievedesired #oal4  1

  // print results  -ystem.out.printlnins " ins o " %0(

  -ystem.out.println"Percent o #ames on A " &66.6 * ins / %0(  -ystem.out.println"3v# Y )ets A " &.6 * )ets / %0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 34/180

a$tors.java

Below is the syntax highlighted version of ,a(tors.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Vactors.java * Execution: java Vactors G ** Computes te prime actoriQation o G usin# )rute orce. * * $ java Vactors K& * %e prime actoriQation o K& is: 8 8 8 8* * $ java Vactors &K * %e prime actoriQation o &K is: 9 9 9 8 '

 * * $ java Vactors ?????????? * %e prime actoriQation o ?????????? is: 9 9 && ?& 9'& D6D&* * $ java Vactors ??????????????8 * %e prime actoriQation o ??????????????8 is: ??????????????8 ** $ java Vactors &666666&?666666?D * %e prime actoriQation o &666666&?666666?D is: &6666666' &6666666'* * $ java Vactors &6666666&?6666666?D * %e prime actoriQation o &6666666&?6666666?D is: &66666666' &66666666' * * $ java Vactors D96&&&&&D'@@@@@?D

 * %e prime actoriQation o D96&&&&&D'@@@@@?D is: 86888888?8 86888888?8* * Can use tese or timin# tests 5 )i##est 8, , D, &9, &@, and &K di#itprimes * $ java Vactors DD' * $ java Vactors DDDDK8 * $ java Vactors DDDDDDD8' * $ java Vactors DDDDDDDDDDKD * $ java Vactors DDDDDDDDDDDDDKD * $ java Vactors DDDDDDDDDDDDDDDDKD * * >emars * 5555555

 * 5 %ests i*i SA G instead o i SA G or eiciency. * * 5 %e last to examples still tae a e minutes. *  *************************************************************************/

pu)lic class Vactors +

  pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 35/180

  // command5line ar#ument  lon# n A Lon#.parseLon#ar#s60(

  -ystem.out.print"%e prime actoriQation o " n " is: "0(

  // or eac potential actor i  or lon# i A 9( i*i SA n( i0 +

  // i i is a actor o G, repeatedly divide it out  ile n $ i AA 60 +  -ystem.out.printi " "0(

n A n / i(  1  1

  // i )i##est actor occurs only once, n M &  i n M &0 -ystem.out.printlnn0(  else -ystem.out.println0(  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" )h! #eb 3 1%"+"& (S) 2012.

)rime.java

Below is the syntax highlighted version of rime.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Primes.java * Execution: java Primes G ** =etermines eter or not G is prime. * * $ java Prime K& * K& is not prime * * $ java Prime &' * &' is prime * * $ java Prime 86K?89?D&?KD * 86K?89?D&?KD is not prime * *  *************************************************************************/

pu)lic class Prime +

  pu)lic static void main-trin# ar#s0 +lon# G A Lon#.parseLon#ar#s60(

  )oolean isPrime A true(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 36/180

  i G S 90 isPrime A alse(

  // try all possi)le actors i o G  // i i G as a actor, ten it as one less tan or eFual tosFrtG0,  // so or eiciency e only need to cec i SA sFrtG0 oreFuivalently i*i SA G  or lon# i A 9( i*i SA G( i0 +

  // i i divides evenly into G, G is not prime, so )rea out oloop  i G $ i AA 60 +  isPrime A alse(  )rea(  1  1

  // print out eter or not G is prime  i isPrime0 -ystem.out.printlnG " is prime"0(  else -ystem.out.printlnG " is not prime"0(

  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )h! #eb 2 1+"'+"1' (S) 2012.

ive)er%ine.java

Below is the syntax highlighted version of ,iveer)ine.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac VivePerLine.java * Execution: java VivePerLine ** Print te inte#ers rom &666 to 9666, @ per line. * * $ java VivePerLine *  *************************************************************************/

pu)lic class VivePerLine +

pu)lic static void main-trin# ar#s0 +

  // print inte#ers rom &666 to 9666, @ per line  int start A &666, end A 9666(  or int i A start( i SA end( i0 +  -ystem.out.printi " "0(  i i $ @ AA ?0 -ystem.out.println0(  1  -ystem.out.println0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 37/180

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.Ruler9.java

Below is the syntax highlighted version of uler/.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac >ulerG.java * Execution: java >ulerG G ** Prints te relative len#ts o te su)divisions on a ruler or * order G. ** $ java >ulerG 8 * &* & 9 &* & 9 & 8 & 9 &* * $ java >ulerG @ * &* & 9 &* & 9 & 8 & 9 &

* & 9 & 8 & 9 & ? & 9 & 8 & 9 &* & 9 & 8 & 9 & ? & 9 & 8 & 9 & @ & 9 & 8 & 9 & ? & 9 & 8 & 9 &

** $ java >ulerG &66 * a lot o output, ten * Exception in tread "main" java.lan#.utemoryError *  *************************************************************************/

pu)lic class >ulerG +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  // ruler o order 6  -trin# ruler A " "(

  // repeat G times  or int i A &( i SA G( i0 +

  // concatenate a ruler o order 6, te num)er i, and a ruler oorder 6  ruler A ruler i ruler(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 38/180

  // print out te inal result  -ystem.out.printlnruler0(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

un$tionro,th.java

Below is the syntax highlighted version of ,un(tion>rowth.java from §1.< 5onditionals and

)oo#s.

/************************************************************************* * Compilation: javac VunctionJrot.java * Execution: java VunctionJrot * * Print out ln G, G, G lo# G, GT9, GT8 or G A 9, ?, K, ..., 96?K. * * $ java VunctionJrot * lo# G G G lo# G GT9 GT8 * 6 9 & ? K * & ? @ & ? * 9 K & ? @&9 * 9 & ?? 9@ ?6D * 8 89 &&6 &69? 89'K * ? ? 9 ?6D 99&?? * ? &9K 9& &8K? 96D'&@9 * @ 9@ &?&D @@8 &'''9& * @&9 8&D? 99&?? &8?9&''9K * &69? '6D' &6?K@' &6'8'?&K9? * ' 96?K &@&@ ?&D?86? K@KDD8?@D9 **************************************************************************/

pu)lic class VunctionJrot +

  pu)lic static void main-trin# ar#s0 +

-ystem.out.println"lo# G ZtG ZtG lo# GZtGT9 ZtGT8"0(  or lon# i A 9( i SA 96?K( i *A 90 +  -ystem.out.printint0 at.lo#i00(  -ystem.out.print!Zt!0( // ta) caracter  -ystem.out.printi0(  -ystem.out.print!Zt!0(

-ystem.out.printint0 i * at.lo#i000(  -ystem.out.print!Zt!0(

-ystem.out.printi * i0(  -ystem.out.print!Zt!0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 39/180

  -ystem.out.printi * i * i0(  -ystem.out.println0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Ramanujan.java

Below is the syntax highlighted version of amanujan.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac >amanujan.java * Execution: java >amanujan G ** Prints out any num)er )eteen & and G tat can )e expressed as te * sum o to cu)es in to or more0 dierent ays. * * $ java >amanujan &'9K * * $ java >amanujan &'9D * &'9D A &T8 &9T8 A DT8 &6T8 * * $ java >amanujan &6666 * &'9D A &T8 &9T8 A DT8 &6T8 * ?&6? A 9T8 &T8 A DT8 &@T8

 * * $ java >amanujan &66666 * &'9D A &T8 &9T8 A DT8 &6T8 * ?&6? A 9T8 &T8 A DT8 &@T8 * &8K89 A 9T8 9?T8 A &KT8 96T8 * 8D8&9 A 9T8 8?T8 A &@T8 88T8 * ?K8 A 8T8 8T8 A 9'T8 86T8 * 89K89 A ?T8 89T8 A &KT8 86T8 * ?6688 A DT8 8?T8 A &T8 88T8 * 96K8 A &6T8 9'T8 A &DT8 9?T8 * @'9K A &9T8 ?6T8 A 8&T8 88T8 * ?989 A &'T8 8DT8 A 9T8 8T8 * * $ java >amanujan &66666666 sort 5n // sort results numerically in 2nix * &'9D A &T8 &9T8 A DT8 &6T8 * ... * K'@8D8&D A &'T8 ?8T8 A 99KT8 ?98T8 * K'@8D8&D A &'T8 ?8T8 A 9@@T8 ?&?T8 * K'@8D8&D A 99KT8 ?98T8 A 9@@T8 ?&?T8 * ... * * Bu#s * 5555

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 40/180

 * ; a num)er can )e expressed as a sum o cu)es in more tan to * dierent ays, te pro#ram prints some duplicates. *  *************************************************************************/

pu)lic class >amanujan +

  pu)lic static void main-trin# ar#s0 +

// read in one command5line ar#ument  int G A ;nte#er.parse;ntar#s60(

  // or eac a, ), c, d, cec eter aT8 )T8 A cT8 dT8  or int a A &( a SA G( a0 +  int a8 A a*a*a(  i a8 M G0 )rea(

  // start at a to avoid print out duplicate  or int ) A a( ) SA G( )0 +  int )8 A )*)*)(

  i a8 )8 M G0 )rea(

  // start at a & to avoid printin# out duplicates  or int c A a &( c SA G( c0 +  int c8 A c*c*c(  i c8 M a8 )80 )rea(

  // start at c to avoid printin# out duplicates  or int d A c( d SA G( d0 +  int d8 A d*d*d(  i c8 d8 M a8 )80 )rea(

  i c8 d8 AA a8 )80 +  -ystem.out.printa8)80 " A "0(  -ystem.out.printa "T8 " ) "T8 A "0(

-ystem.out.printc "T8 " d "T8"0(-ystem.out.println0(

  1  1  1  1  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Dragon.java

Below is the syntax highlighted version of $ragon.java from §1.< 5onditionals and )oo#s. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 41/180

/************************************************************************* * Compilation: javac =ra#on.java * Execution: java =ra#on G ** Prints te instructions or drain# a dra#on curve o orders G. ** $ java =ra#on 6 * V ** $ java =ra#on & * VLV ** $ java =ra#on 9 * VLVLV>V ** $ java =ra#on 8 * VLVLV>VLVLV>V>V ** $ java =ra#on ?

 * VLVLV>VLVLV>V>VLVLVLV>V>VLV>V>V ** $ java =ra#on @ * VLVLV>VLVLV>V>VLVLVLV>V>VLV>V>VLVLVLV>VLVLV>V>V>VLVLV>V>VLV>V>V *  *************************************************************************/

pu)lic class =ra#on +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  -trin# dra#on A "V"(  -trin# no#ard A "V"(  -trin# temp(

  or int i A &( i SA G( i0 +  temp A dra#on( // save aay copy o dra#on  dra#on A dra#on "L" no#ard(  no#ard A temp ">" no#ard( // use old value o dra#on  1  -ystem.out.printlndra#on0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011. IB9.java

Below is the syntax highlighted version of I9B/.java from §1.< 5onditionals and )oo#s.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 42/180

/************************************************************************* * Compilation: javac ;-BG.java * Execution: java ;-BG G ** =etermines te cec di#it o an ;-BG num)er #iven te irst D di#its. * * 3n ;-BG num)er is le#al i it consists o &6 di#its and * d[& 9*d[9 8*d[8 ... &6*d[&6 is a multiple o &&. * Vor example, 6596&58&?@95@ is le#al since * &*@ 9*9 8*@ ?*? @*& *8 '*& K*6 D*9 &6*6 A KK * and KK is a multiple o &&. * * -ample execution: * * $ java ;-BG 696&8&?@9 * %e ull ;-BG num)er is 96&8&?@9@. *  *************************************************************************/

pu)lic class ;-BG +

  pu)lic static void main-trin# ar#s0 +

// read in one command5line ar#ument  int G A ;nte#er.parse;ntar#s60(

  // compute te ei#ted sum o te di#its, rom ri#t to let  int sum A 6(  or int i A 9( i SA &6( i0 +  int di#it A G $ &6( // ri#tmost di#it  sum A sum i * di#it(  G A G / &6(  1 

// print out cec di#it, use or &6  -ystem.out.print"%e ull ;-BG num)er is " ar#s60(  i sum $ && AA &0 -ystem.out.println""0(  else i sum $ && AA 60 -ystem.out.println"6"0(  else -ystem.out.println&& 5 sum $ &&00(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

 Thue6orse.java

Below is the syntax highlighted version of Thue?orse.java from §1.< 5onditionals and )oo#s.

/*************************************************************************

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 43/180

 * Compilation: javac %ueorse.java * Execution: java %ueorse G ** Prints te %ue5orse seFuence, ic is deined as ollos ** -tart it 6, and repeatedly lip all te )its and concatenate * it onto te ori#inal strin#. * * $ java %ueorse 6 * 6 ** $ java %ueorse & * 6& ** $ java %ueorse 9 * 6&&6 * * $ java %ueorse 9 * 6&&6&66& *

 * $ java %ueorse ? * 6&&6&66&&66&6&&6 * * $ java %ueorse @ * 6&&6&66&&66&6&&6&66&6&&66&&6&66& *  *************************************************************************/

pu)lic class %ueorse +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  -trin# tue A "6"(  -trin# morse A "&"(  -trin# t, m( // temporary values

  or int i A &( i SA G( i0 +  t A tue( // save aay values  m A morse(  tue A m(  morse A t(  1  -ystem.out.printlntue0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

in.java

Below is the syntax highlighted version of 9in.java from §1.< 5onditionals and )oo#s. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 44/180

/************************************************************************* * Compilation: javac -in.java * Execution: java -in x ** Prints out sinx0 usin# %aylor expansion. ** sin x A x 5 xT8/8O xT@/@O 5 xT'/'O ... * * $ java sin java -in 6.@98@DK''@@DK9DD * 6.@666666666666669 * * Gote: sinpi/0 A sin6.@98@DK''@@DK9DD...0 A &/9 * * We use identity sinx0 A sinx 9 P;0 to pre5process * x to )e )eteen 59 P; and 9 P;. 7es, $ ors it dou)lesO *  *************************************************************************/

pu)lic class -in +

  pu)lic static void main-trin# ar#s0 +dou)le x A =ou)le.parse=ou)lear#s60(

  // convert x to an an#le )eteen 59 P; and 9 P;  x A x $ 9 * at.P;0(

  // compute te %aylor series approximation  dou)le term A &.6( // it term A xTi / iO  dou)le sum A 6.6( // sum o irst i terms in taylor series

  or int i A &( term OA 6.6( i0 +  term *A x / i0(  i i $ ? AA &0 sum A term(  i i $ ? AA 80 sum 5A term(  1  -ystem.out.printlnsum0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

6onteHall.java

Below is the syntax highlighted version of ?onteHall.java from §1.< 5onditionals and )oo#s. 

/************************************************************************* * Compilation: javac onteHall.java * Execution: java onteHall G ** Plays te onte Hall #ame G times it te sitcin# strate#y

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 45/180

 * and reports te raction o #ames on. * * -ample execution: * * $ java onteHall &6666666 * Vraction o #ames on A 6.@K * * * Gote: true innin# pro)a)ility A 9/8. *  *************************************************************************/

pu)lic class onteHall +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60( // Y trials

  int ins A 6( // Y times you in )y sitcin#

  // repeat experiment G timesor int i A 6( i S G( i0 +

  // ost ides priQe )eind & o 8 doors uniormly at random  int priQe A int0 8 * at.random00(

  // contestant selects & o 8 doors uniormly at random  int coice A int0 8 * at.random00(

  // at random, ost reveals an uncosen door not containin# priQe  int reveal(  do +  reveal A int0 8 * at.random00(  1 ile reveal AA coice0 reveal AA priQe00(

  // ac to compute te remainin# door ic contestent sitces to  int oter A 6 & 9 5 reveal 5 coice(

  // sitcin# leads to a in  i oter AA priQe0 ins(  1

// avoid inte#er division  -ystem.out.println"Vraction o #ames on A " &.6 * ins / G0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

RollDie.java

Below is the syntax highlighted version of oll$ie.java from §1.< 5onditionals and )oo#s. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 46/180

/************************************************************************* * Compilation: javac >oll=ie.java * Execution: java >oll=ie * * -imulate te roll o a air six5sided die * and print te resultin# num)er. * * $ java >oll=ie * ? * * $ java >oll=ie * & *  *************************************************************************/

pu)lic class >oll=ie +  pu)lic static void main-trin# ar#s0 +  int -;=E- A ( // o many sides on te die4

  // roll sould )e & trou# -;=E-

  int roll A int0 at.random0 * -;=E-0 &(

  // print result  -ystem.out.printlnroll0(

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Roll%oa#e#Die.java

Below is the syntax highlighted version of oll)oaded$ie.java from §1.< 5onditionals and

)oo#s.

/************************************************************************* * Compilation: javac >ollLoaded=ie.java * Execution: java >ollLoaded=ie

 * * -imulate te roll o a loaded six5sided die, ere te values * &, 9, 8, ?, and @ appear it pro)a)ility &/K and te value  * appears it pro)a)lity 8/K, and print te resultin# num)er. * * $ java >ollLoaded=ie * ? * * $ java >ollLoaded=ie *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 47/180

 *  *************************************************************************/

pu)lic class >ollLoaded=ie +  pu)lic static void main-trin# ar#s0 +

  // dou)le in te ran#e 6.6, &.60  dou)le r A at.random0(

  // inte#er in te ran#e & to it desired pro)a)ilities  int roll(  i r S &.6/K.60 roll A &(  else i r S 9.6/K.60 roll A 9(  else i r S 8.6/K.60 roll A 8(  else i r S ?.6/K.60 roll A ?(  else i r S @.6/K.60 roll A @(  else roll A (

  // print result  -ystem.out.printlnroll0(

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Hurri$ane.java

Below is the syntax highlighted version of Hurri(ane.java from §1.< 5onditionals and )oo#s. 

/************************************************************************* * Compilation: javac Hurricane.java * Execution: java Hurricane G ** >eads in te ind speed in miles per our0 and reports eter it is * a urricane, and i so, eter it is Class &, 9, 8, ? or @ accordin# * to te -air5-impson scale. * * >eerence: ttp://.marineaypoints.com/marine/ind.stml * * $ java Hurricane 9@ * Got a urricane * * $ java Hurricane &8@ * Class ? urricane *  *************************************************************************/

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 48/180

pu)lic class Hurricane +

  pu)lic static void main-trin# ar#s0 +int ind-peed A ;nte#er.parse;ntar#s60(

  i ind-peed S @0 -ystem.out.println"Got a urricane"0(  else i ind-peed S D0 -ystem.out.println"Class & urricane"0(

else i ind-peed S &&&0 -ystem.out.println"Class 9 urricane"0(else i ind-peed S &8&0 -ystem.out.println"Class 8 urricane"0(else i ind-peed S &@@0 -ystem.out.println"Class ? urricane"0(else -ystem.out.println"Class @ urricane"0(

11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

 Triangle.java

Below is the syntax highlighted version of Triangle.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac %rian#le.java * Execution: java %rian#le G ** Prints out an G5)y5G trian#ular pattern lie te one )elo.

 * * $ java %rian#le * * * * * * ** . * * * * * * . . * * * * * . . . * * * * . . . . * * * . . . . . * *  *************************************************************************/

pu)lic class %rian#le +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  // loop G times, one or eac ro  or int i A 6( i S G( i0 +

  // print j periods  or int j A 6( j S i( j0  -ystem.out.print". "0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 49/180

  // print G5i asteriss  or int j A 6( j S G5i( j0  -ystem.out.print"* "0(

  // print a ne line  -ystem.out.println0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

'.java

Below is the syntax highlighted version of @x.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Ex.java * Execution: java Ex G ** Prints out an o radius G lie te one )elo. * * $ java Ex 8 * * . . . . . ** . * . . . * .* . . * . * . .* . . . * . . .

* . . * . * . .* . * . . . * .* * . . . . . ** * $ java Ex @ * * . . . . . . . . . ** . * . . . . . . . * .* . . * . . . . . * . .* . . . * . . . * . . .* . . . . * . * . . . .* . . . . . * . . . . .* . . . . * . * . . . .* . . . * . . . * . . .* . . * . . . . . * . .* . * . . . . . . . * .* * . . . . . . . . . **  *************************************************************************/

pu)lic class Ex +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 50/180

  or int i A 5G( i SA G( i0 +  or int j A 5G( j SA G( j0 +  i i AA 5j0 i AA j00 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Bo,Tie.java

Below is the syntax highlighted version of BowTie.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Bo%ie.java * Execution: java Bo%ie G ** Prints out a )otie o "radius" G lie te one )elo. * * $ java Bo%ie 8 * * . . . . . ** * * . . . * ** * * * . * * *

* * * * * * * ** * * * . * * ** * * . . . * ** * . . . . . **  *************************************************************************/

pu)lic class Bo%ie +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  or int i A 5G( i SA G( i0 +  or int j A 5G( j SA G( j0 +  i i*i SA j*j0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 51/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Diamon#.java

Below is the syntax highlighted version of $iamond.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac =iamond.java * Execution: java =iamond G ** Prints out a 9G&5)y59G& diamond lie te one )elo. * * $ java =iamond ? * . . . . * . . . .* . . . * * * . . .

* . . * * * * * . .* . * * * * * * * .* * * * * * * * * ** . * * * * * * * .* . . * * * * * . .* . . . * * * . . .* . . . . * . . . .*  *************************************************************************/

pu)lic class =iamond +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  or int i A 5G( i SA G( i0 +  or int j A 5G( j SA G( j0 +  i at.a)si0 at.a)sj0 SA G0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Heart.java

Below is the syntax highlighted version of Heart.java from §1.< 5onditionals and )oo#s.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 52/180

/************************************************************************* * Compilation: javac Heart.java * Execution: java Heart G ** Prints out a eart. * * $ java Heart &@ * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .* . . . . . . . . . . . . * * * * * * * . . . . . . . * * * * * ** . . . . . . . . . . . .* . . . . . . . . . . * * * * * * * * * * * . . . * * * * * * * * * ** . . . . . . . . . .* . . . . . . . . . * * * * * * * * * * * * * . * * * * * * * * * * * ** . . . . . . . . .* . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . . .* . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . .* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * . . . . . .* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * . . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

* * * . . . . .* . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * * . . . . .* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * . . . . . .* . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** * . . . . . .* . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . .

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 53/180

 * . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . . .* . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . . . .* . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * * * ** . . . . . . . . . .* . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * * * ** . . . . . . . . . . .* . . . . . . . . . . . . * * * * * * * * * * * * * * * * * * * ** . . . . . . . . . . . .* . . . . . . . . . . . . . * * * * * * * * * * * * * * * * * ** . . . . . . . . . . . . .* . . . . . . . . . . . . . . * * * * * * * * * * * * * * * ** . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . * * * * * * * * * * * * * ** . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . * * * * * * * * * * * ** . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . * * * * * * * * * ** . . . . . . . . . . . . . . . . .

* . . . . . . . . . . . . . . . . . . * * * * * * * ** . . . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . . . * * * * * ** . . . . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . . . . * * * ** . . . . . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . . . . . * ** . . . . . . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . . . . . .* . . . . . . . . . . . . . . . . . . . . . .

* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . .*  *************************************************************************/

pu)lic class Heart +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  or int i A 58*G/9( i SA G( i0 +  or int j A 58*G/9( j SA 8*G/9( j0 +

  // inside eiter diamond or to circles  i at.a)si0 at.a)sj0 S G0  5G/95i0 * 5G/95i0 G/95j0 * G/95j0 SA G*G/90  5G/95i0 * 5G/95i0 5G/95j0 * 5G/95j0 SA G*G/90

  0  -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 54/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Gir$le.java

Below is the syntax highlighted version of 5ir(le.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Circle.java * Execution: java Circle G ** Prints out a circle o radius G lie te one )elo. * * $ java Circle @ * . . . . . * . . . . .* . . * * * * * * * . .

* . * * * * * * * * * .* . * * * * * * * * * .* . * * * * * * * * * .* * * * * * * * * * * ** . * * * * * * * * * .* . * * * * * * * * * .* . * * * * * * * * * .* . . * * * * * * * . .* . . . . . * . . . . .*  *************************************************************************/

pu)lic class Circle +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  or int i A 5G( i SA G( i0 +  or int j A 5G( j SA G( j0 +  i i*i j*j SA G*G0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

uler.java

Below is the syntax highlighted version of @uler.java from §1.< 5onditionals and )oo#s.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 55/180

/************************************************************************* * Compilation: javac Euler.java * Execution: java Euler G *

* %ests eter tere are any ive positive inte#ers tat satisy * aT@ )T@ cT@ dT@ A eT@. ;n &'D Euler conjectured tat no suc * solutions exists, )ut is conjecture as disproved in &D usin# * a metod lie te one )elo. * * %e pro#ram reads in a command line parameter G and prints out all * solutions it a SA ) SA c SA d SA e SA G. >estrictin# attention * to solutions o tis orm only eliminates duplicates and maes * te pro#ram aster since e ave many eer possi)ilities to try * '@,DD8,'K6 vs. '@,D8',@66,6660. * * Vor urter eiciency, e use te )rea statement to avoid explicitly * enumeratin# certain tuples a, ), c, d, e0, e.#., i aT@ )T@

 * is already #reater tan eT@, tere is no need to ix speciic * values o c and d and compute aT@ )T@ cT@ dT@. n my system, * tis decreased te runnin# time rom 8 minutes to 8@ seconds. * * $ java Euler &66 * * $ java Euler &@6 * 9'T@ K?T@ &&6T@ &88T@ A &??T@ // taes a)out 8@ seconds * *  *************************************************************************/

pu)lic class Euler +

  pu)lic static void main-trin# ar#s0 +lon# G A Lon#.parseLon#ar#s60(

  lon# a@, )@, c@, d@, e@(

  or lon# e A &( e SA G( e0 +  e@ A e*e*e*e*e(

  // restrict searc to a SA ) SA c SA d SA e or eiciency  or lon# a A &( a SA G( a0 +  a@ A a*a*a*a*a(  i a@ a@ a@ a@ M e@0 )rea(

  or lon# ) A a( ) SA G( )0 +

  )@ A )*)*)*)*)(  i a@ )@ )@ )@ M e@0 )rea(

  or lon# c A )( c SA G( c0 +  c@ A c*c*c*c*c(  i a@ )@ c@ c@ M e@0 )rea(

  or lon# d A c( d SA G( d0 +  d@ A d*d*d*d*d(  i a@ )@ c@ d@ M e@0 )rea(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 56/180

  i a@ )@ c@ d@ AA e@0  -ystem.out.printlna "T@ " ) "T@ " c "T@ " d "T@ A " e "T@"0(

1  1  1  1  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

)epys.java

Below is the syntax highlighted version of e#ys.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Pepys.java * Execution: java Pepys G ** Wic is more liely: at least one & in rolls o a air die, or * at least to &!s in &9 rolls o a air die4 * * java Pepys &6666666 * 6.@&K@

 * 6.&KK&K *  *************************************************************************/

pu)lic class Pepys +pu)lic static void main-trin# ar#s0 +

  int G A ;nte#er.parse;ntar#s60(

  // at least one & in rolls  int cnt& A 6(  or int i A 6( i S G( i0 +  int ones A 6(  or int j A 6( j S ( j0  i * at.random0 S &0  ones(  i ones MA &0 cnt&(  1

  // at least to &!s in &9 rolls  int cnt9 A 6(  or int i A 6( i S G( i0 +  int ones A 6(  or int j A 6( j S &9( j0

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 57/180

  i * at.random0 S &0  ones(  i ones MA 90 cnt9(  1

  -ystem.out.println&.6 * cnt& / G0(  -ystem.out.println&.6 * cnt9 / G0(

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

)al.java

Below is the syntax highlighted version of al.java from §1.< 5onditionals and )oo#s.

/************************************************************************* * Compilation: javac Pal.java * Execution: java Pal G ** $ java Pal & * && * * $ java Pal 9

 * &&9&& * * $ java Pal 8 * 8&&9&&8 * * $ java Pal ? * 8&&9&&8?8&&9&&8 * * $ java Pal @ * @8&&9&&8?8&&9&&8@ *  *************************************************************************/

pu)lic class Pal +  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(  -trin# s A ""(  or int i A &( i SA G( i0 +  i i $ 9 AA 60 s A s i s(  else s A i s i(  1  -ystem.out.printlns0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 58/180

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.=rtBug.java

Below is the syntax highlighted version of 9=rtBug.java from §1.< 5onditionals and )oo#s. 

/************************************************************************* * Compilation: javac -FrtBu#.java * Execution: java -Frt c ** Computes te sFuare root o a nonne#ative num)er c usin# * Geton!s metod: * 5 initialiQe t A c * 5 replace t it te avera#e o c/t and t * 5 repeat until desired accuracy reaced 2-;GJ W>GJ CG=;%;G ** $ java -FrtBu# 9 * &.?&?9&8@98'86D@ * * $ java -FrtBu# &666666 * &666.6 *

* $ java -FrtBu# 6.? * 6.89?@@@89688'@D ** $ java -FrtBu# &6?K@'@ * &698.DDD@&&'&K88 * * $ java -FrtBu# 6 * 6.6 * * $ java -FrtBu# &???? * ininite loop * * $ java -FrtBu# &e5@6 * &.6E5@6 * ron# anser * * * * <non )u#s * 5555555555 * 5 use te loop5continuation condition in -Frt.java or relia)le * results *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 59/180

  *************************************************************************/

pu)lic class -FrtBu# +pu)lic static void main-trin# ar#s0 +

// read in te command5line ar#ument  dou)le c A =ou)le.parse=ou)lear#s60(

  dou)le t A c( // estimate o te sFuare root o c  dou)le EP-;LG A &e5&@( // relative error tolerance

  // repeatedly apply Geton update step until desired precision isacieved  ile at.a)st*t 5 c0 M EP-;LG0 +  t A c/t t0 / 9.6(  1

  // print out te estimate o te sFuare root o c  -ystem.out.printlnt0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 04"'4"+4 (S) 2011.

Arrays.java

Below is the syntax highlighted version of Arrays.java from §1. Arrays. 

/************************************************************************* * Compilation: javac 3rrays.java * Execution: java 3rrays * * %ypical array processin# code. * * $ java 3rrays @ * a * 5555555555555555555 * 6.6?K@&D??9'8K'98'' * 6.K8&&@@6K6KD@'D * 6.@9KKD@'@6@?D'9 * 6.@6@8@D89&@&?'@D * 6.&9899@&D&'KK * * a A =\98'8 * * max A 6.K8&&@@6K6KD@'D * avera#e A 6.@668889D6'D89K *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 60/180

 * ) * 5555555555555555555 * 6.&9899@&D&'KK * 6.@6@8@D89&@&?'@D * 6.@9KKD@'@6@?D'9 * 6.K8&&@@6K6KD@'D * 6.6?K@&D??9'8K'98'' * * dot product o a and ) A &.&'D@D?8DD6DD&D8' *  *************************************************************************/

pu)lic class 3rrays +  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(

  // initialiQe to random values )eteen 6 and &  dou)le a A ne dou)leG(  or int i A 6( i S G( i0 +  ai A at.random0(

  1

  // print array values, one per line  -ystem.out.println"a"0(  -ystem.out.println"5555555555555555555"0(  or int i A 6( i S G( i0 +  -ystem.out.printlnai0(  1  -ystem.out.println0(  -ystem.out.println"a A " a0(  -ystem.out.println0(

  // ind te maximum  dou)le max A =ou)le.GEJ3%;]E[;GV;G;%7(  or int i A 6( i S G( i0 +  i ai M max0 max A ai(  1  -ystem.out.println"max A " max0(

  // avera#e  dou)le sum A 6.6(  or int i A 6( i S G( i0 +  sum A ai(  1  -ystem.out.println"avera#e A " sum / G0(

  // copy to anoter array  dou)le ) A ne dou)leG(  or int i A 6( i S G( i0 +  )i A ai(  1

  // reverse te order  or int i A 6( i S G/9( i0 +  dou)le temp A )i(  )i A )G5i5&(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 61/180

  )G5i5& A temp(  1

  // print array values, one per line  -ystem.out.println0(  -ystem.out.println")"0(  -ystem.out.println"5555555555555555555"0(  or int i A 6( i S G( i0 +  -ystem.out.println)i0(  1  -ystem.out.println0(

  // dot product o a and )  dou)le dotProduct A 6.6(  or int i A 6( i S G( i0 +  dotProduct A ai * )i(  1  -ystem.out.println"dot product o a and ) A " dotProduct0(

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

De$8.java

Below is the syntax highlighted version of $e(2.java from §1. Arrays.

/************************************************************************* * Compilation: javac =ec.java * Execution: java =ec * * =eal @9 cards uniormly at random. * * $ java =ec * 3ce o Clu)s * K o =iamonds * @ o =iamonds * ... * K o Hearts *  *************************************************************************/

pu)lic class =ec +  pu)lic static void main-trin# ar#s0 +  -trin# suit A + "Clu)s", "=iamonds", "Hearts", "-pades" 1(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 62/180

  -trin# ran A + "9", "8", "?", "@", "", "'", "K", "D", "&6","Uac", "Iueen", "<in#", "3ce" 1(

  // avoid ardired constants  int -2;%- A suit.len#t(  int >3G<- A ran.len#t(  int G A -2;%- * >3G<-(

  // initialiQe dec  -trin# dec A ne -trin#G(  or int i A 6( i S >3G<-( i0 +  or int j A 6( j S -2;%-( j0 +  dec-2;%-*i j A rani " o " suitj(  1  1

  // sule  or int i A 6( i S G( i0 +  int r A i int0 at.random0 * G5i00(  -trin# t A decr(

  decr A deci(  deci A t(  1

  // print suled dec  or int i A 6( i S G( i0 +  -ystem.out.printlndeci0(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

ample.java

Below is the syntax highlighted version of 9am#le.java from §1. Arrays.

/************************************************************************* * Compilation: javac -ample.java * Execution: java -ample G * * %is pro#ram taes to command5line ar#uments and G and produces * a random sample o o te inte#ers rom 6 to G5&. * * $ java -ample ?D * &6 96 6 ? ?6  * * $ java -ample &6 &666

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 63/180

 * @ ?KK 9DK @8? K&& D' K&8 &@ ?9? &6D *  *************************************************************************/

pu)lic class -ample +  pu)lic static void main-trin# ar#s0 +  int A ;nte#er.parse;ntar#s60( // coose tis many elements  int G A ;nte#er.parse;ntar#s&0( // rom 6, &, ..., G5&

  // create permutation 6, &, ..., G5&  int perm A ne intG(  or int i A 6( i S G( i0  permi A i(

  // create random sample in perm6, perm&, ..., perm5&  or int i A 6( i S ( i0 +

  // random inte#er )eteen i and G5&  int r A i int0 at.random0 * G5i00(

  // sap elements at indices i and r  int t A permr(  permr A permi(  permi A t(  1

  // print results  or int i A 6( i S ( i0  -ystem.out.printpermi " "0(  -ystem.out.println0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

GouponGolle$tor.java

Below is the syntax highlighted version of 5ou#on5olle(tor.java from §1. Arrays.

/************************************************************************* * Compilation: javac CouponCollector.java * Execution: java CouponCollector G * * Jiven G distinct card types, o many random cards do you need * do collect )eore you ave at least0 one o eac type4 * %is pro#ram simulates tis random process. * * * $ java CouponCollector &666 * @K8

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 64/180

 * * $ java CouponCollector &666 * ?'' * * $ java CouponCollector &666666 * &9'K9'8 *  *************************************************************************/

pu)lic class CouponCollector +  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60( // num)er o card types  )oolean ound A ne )ooleanG( // oundi A true i card i as)een collected  int cardcnt A 6( // total num)er o cardscollected  int valcnt A 6( // num)er o distinct cards 

// repeatedly coose a random card and cec eter it!s a ne one  ile valcnt S G0 +

  int val A int0 at.random0 * G0( // random card )eteen 6and G5&  cardcnt( // e collected one morecard  i Ooundval0 valcnt( // it!s a ne card type  oundval A true( // update ound  1

  // print te total num)er o cards collected  -ystem.out.printlncardcnt0(  11

)rimeieve.java

Below is the syntax highlighted version of rime9ieve.java from §1. Arrays.

/************************************************************************* * Compilation: javac Prime-ieve.java * Execution: java 5mx&&66m Prime-ieve G ** Computes te num)er o primes less tan or eFual to G usin# * te -ieve o Eratostenes. * * $ java Prime-ieve 9@ * %e num)er o primes SA 9@ is D * * $ java Prime-ieve &66 * %e num)er o primes SA &66 is 9@

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 65/180

 * * $ java 5mx&66m Prime-ieve &66666666 * %e num)er o primes SA &66666666 is @'&?@@ * * $ java Prime-ieve 5mx&&66m &666666666* %e num)er o primes SA &666666666 is @6K?'@8? ** * %e &&6B and &&66B is te amount o memory you ant to allocate * to te pro#ram. ; your computer as less, mae tis num)er smaller, * )ut it may prevent you rom solvin# te pro)lem or very lar#e * values o G. * * * G Primes SA G * 555555555555555555555555555555555 * &6 ?* &66 9@* &,666 &K* &6,666 &,99D

* &66,666 D,@D9* &,666,666 'K,?DK* &6,666,666 ?,@'D* &66,666,666 @,'&,?@@* &,666,666,666 @6,K?',@8?*  *************************************************************************/

pu)lic class Prime-ieve +  pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  // initially assume all inte#ers are prime  )oolean isPrime A ne )ooleanG &(  or int i A 9( i SA G( i0 +  isPrimei A true(  1

  // mar non5primes SA G usin# -ieve o Eratostenes  or int i A 9( i*i SA G( i0 +

  // i i is prime, ten mar multiples o i as nonprime  // suices to consider mutiples i, i&, ..., G/i  i isPrimei0 +  or int j A i( i*j SA G( j0 +  isPrimei*j A alse(

  1  1  1

  // count primes  int primes A 6(  or int i A 9( i SA G( i0 +  i isPrimei0 primes(  1  -ystem.out.println"%e num)er o primes SA " G " is " primes0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 66/180

  11

HugeArray.java

Below is the syntax highlighted version of HugeArray.java from §1. Arrays.

/************************************************************************* * Compilation: javac Hu#e3rray.java * Execution: java Hu#e3rray * * 3ttempts to create an array o siQe GT? or G A &666. * * %is pro#ram compiles cleans.

 * Wen G is &666, it leads to te olloin# error * * java.lan#.Ge#ative3rray-iQeException ** )ecause &666T? overlos an int and results in a ne#ative inte#er. * ** * Wen G is 966, it leads to te olloin# error * * java.lan#.utemoryError: >eFuested array siQe exceeds ] limit * *  *************************************************************************/

pu)lic class Hu#e3rray +

pu)lic static void main-trin# ar#s0 +int G A &666(

  int a A ne intG*G*G*G(  11

Deal.java

Below is the syntax highlighted version of $eal.java from §1. Arrays. 

/************************************************************************* * Compilation: javac =eal.java

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 67/180

 * Execution: java =eal PL37E>- * * =eal @5card ands at random to te #iven num)er o players. * * $ java =eal 8 * ? o -pades * D o -pades * 3ce o Hearts * D o Clu)s * D o =iamonds * * o -pades * &6 o Hearts * Iueen o Hearts * K o Hearts * <in# o -pades * * ' o Hearts * K o =iamonds * Iueen o -pades

 * 8 o -pades * ? o =iamonds *  *************************************************************************/

pu)lic class =eal +  pu)lic static void main-trin# ar#s0 +  int C3>=-[PE>[PL37E> A @(

  // num)er o players  int PL37E>- A ;nte#er.parse;ntar#s60(

  -trin# suit A + "Clu)s", "=iamonds", "Hearts", "-pades" 1(  -trin# ran A + "9", "8", "?", "@", "", "'", "K", "D", "&6","Uac", "Iueen", "<in#", "3ce" 1(

  // avoid ardired constants  int -2;%- A suit.len#t(  int >3G<- A ran.len#t(  int C3>=- A -2;%- * >3G<-(

  i C3>=-[PE>[PL37E> * PL37E>- M C3>=-0 tro ne>untimeException"%oo many players"0(

  // initialiQe dec

  -trin# dec A ne -trin#C3>=-(  or int i A 6( i S >3G<-( i0 +  or int j A 6( j S -2;%-( j0 +  dec-2;%-*i j A rani " o " suitj(  1  1

  // sule  or int i A 6( i S C3>=-( i0 +  int r A i int0 at.random0 * C3>=-5i00(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 68/180

  -trin# t A decr(  decr A deci(  deci A t(  1

  // print suled dec  or int i A 6( i S PL37E>- * C3>=-[PE>[PL37E>( i0 +  -ystem.out.printlndeci0(  i i $ C3>=-[PE>[PL37E> AA C3>=-[PE>[PL37E> 5 &0-ystem.out.println0(  1  1

1

.

 Transpose.java

Below is the syntax highlighted version of Trans#ose.java from §1. Arrays.

/************************************************************************* * Compilation: javac %ranspose.java * Execution: java %ranspose D ** %ranspose an G5)y5G matrix in5place, itout creatin# a second * 9= array. * * -u)mitted )y Cristian >u)io. *

  *************************************************************************/

pu)lic class %ranspose +

  pu)lic static void main-trin# ar#s0 +

  // create G5)y5G matrix  int G A ;nte#er.parse;ntar#s60(  int a A ne intGG(  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  aij A G*i j(

  1  1

  // print out initial matrix  -ystem.out.println"Beore"0(  -ystem.out.println"555555"0(  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  -ystem.out.print"$?d", aij0(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 69/180

  -ystem.out.println0(  1

  // transpose in5place  or int i A 6( i S G( i0 +  or int j A i&( j S G( j0 +  int temp A aij(  aij A aji(  aji A temp(  1  1

  // print out transposed matrix  -ystem.out.println0(  -ystem.out.println"3ter"0(  -ystem.out.println"555555"0(  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  -ystem.out.print"$?d", aij0(  1

  -ystem.out.println0(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

elfAvoi#ing+al8.java

Below is the syntax highlighted version of 9elfAvoidingWal2.java from §1. Arrays.

/************************************************************************* * Compilation: javac -el3voidin#Wal.java * Execution: java -el3voidin#Wal G % * * Jenerate % sel5avoidin# als o len#t G. * >eport te raction o time te random al is non sel5intersectin#. *  *************************************************************************/

pu)lic class -el3voidin#Wal +  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60( // lattice siQe  int % A ;nte#er.parse;ntar#s&0( // num)er o trials  int deadEnds A 6( // trials resultin# in a deadend

  // simulate % sel5avoidin# als  or int t A 6( t S %( t0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 70/180

  )oolean a A ne )ooleanGG( // intersections visitedint x A G/9, y A G/9( // current position

  // repeatedly tae a random step, unless you!ve already escaped  ile x M 6 NN x S G5& NN y M 6 NN y S G5&0 +

  // dead5end, so )rea out o loop  i ax5&y NN ax&y NN axy5& NN axy&0 +  deadEnds(  )rea(  1

// mar x, y0 as visited  axy A true(

// tae a random step to unvisited nei#)or  dou)le r A at.random0(

i r S 6.9@0 + i Oax&y0 x( 1  else i r S 6.@60 + i Oax5&y0 x55( 1  else i r S 6.'@0 + i Oaxy&0 y( 1

  else i r S &.660 + i Oaxy5&0 y55( 1  1

1

-ystem.out.println&66*deadEnds/% "$ dead ends"0(1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Inverse)ermutation.java

Below is the syntax highlighted version of Inverseermutation.java from §1. Arrays.

/************************************************************************* * Compilation: javac ;nversePermutation.java * Execution: java ;nversePermutation @ 6 9 8 & ? ** >ead in a permutation rom te command line and print out te inverse * permutation. * * $ java ;nversePermutation @ 6 9 8 & ? * 9 8 ? @ & 6*  *************************************************************************/

pu)lic class ;nversePermutation +pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 71/180

  int G A ar#s.len#t(

  // read in permutation  int a A ne intG(  or int i A 6( i S G( i0  ai A ;nte#er.parse;ntar#si0(

  // cec i valid  )oolean exists A ne )ooleanG(  or int i A 6( i S G( i0 +  i ai S 6 ai MA G existsai0  tro ne >untimeException";nput is not a permutation."0(  existsai A true(  1

  // invert  int ainv A ne intG(  or int i A 6( i S G( i0  ainvai A i(

  // print out  or int i A 6( i S G( i0  -ystem.out.printainvi " "0(  -ystem.out.println0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Ha#amar#.java

Below is the syntax highlighted version of Hadamard.java from §1. Arrays.

/************************************************************************* * Compilation: javac Hadamard.java * Execution: java Hadamard & ** Prints te Hadamard matrix o order G. 3ssumes G is a poer o 9. * * $ java Hadamard 9 * * ** * .* * $ java Hadamard ? * * * * ** * . * .* * * . .* * . . *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 72/180

 *  *************************************************************************/

pu)lic class Hadamard +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  )oolean H A ne )ooleanGG(

  // initialiQe Hadamard matrix o order G  H66 A true(  or int n A &( n S G( n A n0 +  or int i A 6( i S n( i0 +  or int j A 6( j S n( j0 +  Hinj A Hij(  Hijn A Hij(  Hinjn A OHij(  1  1  1

  // print matrix  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  i Hij0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println0(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

)rimeieve.java

Below is the syntax highlighted version of rime9ieve.java from §1. Arrays.

/************************************************************************* * Compilation: javac Prime-ieve.java * Execution: java 5mx&&66m Prime-ieve G ** Computes te num)er o primes less tan or eFual to G usin# * te -ieve o Eratostenes. * * $ java Prime-ieve 9@ * %e num)er o primes SA 9@ is D * * $ java Prime-ieve &66

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 73/180

 * %e num)er o primes SA &66 is 9@ * * $ java 5mx&66m Prime-ieve &66666666 * %e num)er o primes SA &66666666 is @'&?@@ * * $ java Prime-ieve 5mx&&66m &666666666* %e num)er o primes SA &666666666 is @6K?'@8? ** * %e &&6B and &&66B is te amount o memory you ant to allocate * to te pro#ram. ; your computer as less, mae tis num)er smaller, * )ut it may prevent you rom solvin# te pro)lem or very lar#e * values o G. * * * G Primes SA G * 555555555555555555555555555555555 * &6 ?* &66 9@* &,666 &K

* &6,666 &,99D* &66,666 D,@D9* &,666,666 'K,?DK* &6,666,666 ?,@'D* &66,666,666 @,'&,?@@* &,666,666,666 @6,K?',@8?*  *************************************************************************/

pu)lic class Prime-ieve +  pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  // initially assume all inte#ers are prime  )oolean isPrime A ne )ooleanG &(  or int i A 9( i SA G( i0 +  isPrimei A true(  1

  // mar non5primes SA G usin# -ieve o Eratostenes  or int i A 9( i*i SA G( i0 +

  // i i is prime, ten mar multiples o i as nonprime  // suices to consider mutiples i, i&, ..., G/i  i isPrimei0 +  or int j A i( i*j SA G( j0 +

  isPrimei*j A alse(  1  1  1

  // count primes  int primes A 6(  or int i A 9( i SA G( i0 +  i isPrimei0 primes(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 74/180

  -ystem.out.println"%e num)er o primes SA " G " is " primes0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.6ines,eeper.java

Below is the syntax highlighted version of ?ineswee#er.java from §1. Arrays.

/************************************************************************* * Compilation: javac ineseeper.java * Execution: java ineseeper G p ** Creates an xG mineseeper #ame ere eac cell is a )om) it * pro)a)ility p. Prints out te xG #ame and te nei#)orin# )om) * counts. * * -ample execution: * * $ java ineseeper @ &6 6.8 * * . . . . . . . . ** . . . . . . * . . .* . . . . . . . . * ** . . . * * * . . * .* . . . * . . . . . .

* * * & 6 6 6 & & & & ** & & 6 6 6 & * 9 8 8* 6 6 & 9 8 8 9 8 * ** 6 6 9 * * * & 9 * 8* 6 6 9 * ? 9 & & & &* *  *************************************************************************/

pu)lic class ineseeper +pu)lic static void main-trin# ar#s0 +

int A ;nte#er.parse;ntar#s60(  int G A ;nte#er.parse;ntar#s&0(  dou)le p A =ou)le.parse=ou)lear#s90( 

// #ame #rid is &..&..G, )order is used to andle )oundary cases  )oolean )om)s A ne )oolean9G9(  or int i A &( i SA ( i0  or int j A &( j SA G( j0  )om)sij A at.random0 S p0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 75/180

  // print #ame  or int i A &( i SA ( i0 +  or int j A &( j SA G( j0  i )om)sij0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  -ystem.out.println0(  1

  // solij A Y )om)s adjacent to cell i, j0  int sol A ne int9G9(  or int i A &( i SA ( i0  or int j A &( j SA G( j0  // ii, jj0 indexes nei#)orin# cells  or int ii A i 5 &( ii SA i &( ii0  or int jj A j 5 &( jj SA j &( jj0  i )om)siijj0 solij(

  // print solution  -ystem.out.println0(  or int i A &( i SA ( i0 +

  or int j A &( j SA G( j0  i )om)sij0 -ystem.out.print"* "0(  else -ystem.out.printsolij " "0(  -ystem.out.println0(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Ran#om+al8ers.java

Below is the syntax highlighted version of andomWal2ers.java from §1. Arrays. 

/************************************************************************* * Compilation: javac >andomWalers.java * Execution: java >andomWaler G * * -imulates o lon# it taes G random alers startin# at te center * o an G5)y5G #rid to visit every cell in te #rid. *  *************************************************************************/

pu)lic class >andomWalers +

  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(  int x A ne intG( // x positions  int y A ne intG( // y positions

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 76/180

  int cells%o]isit A G*G( // cells let to visit  int steps A 6( // num)er o steps taen  dou)le r(  )oolean visited A ne )ooleanGG( // as te i5j )een visited4

  // start at center  or int i A 6( i S G( i0 +  xi A G/9(  yi A G/9(  1  visitedG/9G/9 A true(  cells%o]isit55(

  // repeat until all cells ave )een visited  ile cells%o]isit M 60 +  steps(

  // move random aler i  or int i A 6( i S G( i0 +

  r A at.random0(  i r SA 6.9@0 + xi( 1  else i r SA 6.@60 + xi55( 1  else i r SA 6.'@0 + yi( 1  else i r SA &.660 + yi55( 1

  // cec i xi, yi0 is inside G5)y5G )oundary and as)een visited  i xi S G NN yi S G NN xi MA 6 NN yi MA 6 NN Ovisitedxiyi0 +  cells%o]isit55(  visitedxiyi A true(  1  1  1

  -ystem.out.printlnsteps0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Birth#ay.java

Below is the syntax highlighted version of Birthday.java from §1. Arrays.

/************************************************************************* * Compilation: javac Birtday.java * Execution: java Birtday =

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 77/180

 ** Computes te num)er o people )y simulation0 tat must enter a room * until to o tem sare a )irtday. 3ssumes )irtdays a uniorm * and independent rom 6 to =5&. ** $ java Birtday 8@ * 9@ * * $ java Birtday 8@ * 99 *  *************************************************************************/

pu)lic class Birtday +

pu)lic static void main-trin# ar#s0 +int = A ;nte#er.parse;ntar#s60( // num)er o days

  int people A 6( // total num)er o people

  // daysd A true i someone )orn on day d( alse oterise  // auto5initialiQed to alse  )oolean days A ne )oolean=(

  ile true0 +  people(  int d A int0 = * at.random00( // inte#er )eteen 6 and =5&  i daysd0 )rea( // to people it te same)irtday, so )rea out o loop  daysd A true( // update daysd  1

  -ystem.out.printlnpeople0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Ho,6any.java

Below is the syntax highlighted version of How?any.java from §1. Arrays. 

/************************************************************************* * Compilation: javac Hoany.java * Execution: java Hoany str& str9 ... strG * * Hoany taes a varia)le num)er o command5line ar#uments * and prints a messa#e reportin# o many tere are. * * $ java Hoany

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 78/180

 * 7ou entered 6 command5line ar#uments. * * $ java Hoany 3lice Bo) Carol * 7ou entered 8 command5line ar#uments. * * $ java Hoany 3lice * 7ou entered & command5line ar#ument. *  *************************************************************************/

pu)lic class Hoany +

  pu)lic static void main-trin# ar#s0 +

  // num)er o command5line ar#uments  int G A ar#s.len#t(

  // output messa#e  -ystem.out.print"7ou entered " G " command5line ar#ument"0(  i G AA & 0 -ystem.out.println"."0(

  else -ystem.out.println"s."0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Dis$reteDistri!ution.java

Below is the syntax highlighted version of $is(rete$istri&ution.java from §1. Arrays.

/************************************************************************* * Compilation: javac =iscrete=istri)ution.java * Execution: java =iscrete=istri)ution reF6 reF& reF9 ... * * >eads in an array o G reFuency counts rom te command line, * and prints out i it pro)a)ility proportional to te it * reFuency count. * * // six eFually liely events * $ java =iscrete=istri)ution & & & & & & * 8 * * $ java =iscrete=istri)ution & & & & & & * 6 * * // six events, one 8x more liely tan te oters * $ java =iscrete=istri)ution & & & & & 8 * @ * * $ java =iscrete=istri)ution & & & & & 8

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 79/180

 * 9 * * $ java =iscrete=istri)ution & & & & & 8 * @ *  *************************************************************************/

pu)lic class =iscrete=istri)ution +  pu)lic static void main-trin# ar#s0 +

  // read in reFuency o occurrence o G values  int G A ar#s.len#t(  int reF A ne intG(  or int i A 6( i S G( i0 +  reFi A ;nte#er.parse;ntar#si0(  1

  // compute total count o all reFuencies  int total A 6(  or int i A 6( i S G( i0 +

  total A reFi(  1

  // #enerate random inte#er it pro)a)ility proportional to reFuency  int r A int0 total * at.random00( // inte#er in 6, total0  int sum A 6(  int event A 5&(  or int i A 6( i S G NN sum SA r( i0 +  sum A reFi(  event A i(  1 

-ystem.out.printlnevent0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

)ermutation.java

Below is the syntax highlighted version of ermutation.java from §1. Arrays. 

/************************************************************************* * Compilation: javac Permutation.java * Execution: java Permutation G ** Prints a pseudorandom permution o te inte#ers 6 trou# G. * * $ java -ule

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 80/180

 * @ 6 9 8 & ?* . * . . . .* . . . . * .* . . * . . .* . . . * . .* . . . . . ** * . . . . .*  *************************************************************************/

pu)lic class Permutation +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  int a A ne intG(

  // insert inte#ers 6..G5&  or int i A 6( i S G( i0  ai A i(

  // sule

  or int i A 6( i S G( i0 +  int r A int0 at.random0 * i&00( // int )eteen 6 and i  int sap A ar(  ar A ai(  ai A sap(  1

  // print permutation  or int i A 6( i S G( i0  -ystem.out.printai " "0(  -ystem.out.println""0(

  // print cecer)oard visualiQation  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  i aj AA i0 -ystem.out.print"* "0(  else -ystem.out.print". "0(  1  -ystem.out.println""0(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011. %R.java

Below is the syntax highlighted version of ),9.java from §1. Arrays.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 81/180

/************************************************************************* * Compilation: javac LV->.java * Execution: java LV-> G ** -imulate a LV-> or G steps and print results. * * $ java LV-> ?6 * 6&66&&66&666666&&666&666&6&&&6&6&6&&&&66 *  *************************************************************************/

pu)lic class LV-> +

  pu)lic static void main-trin# ar#s0 +// initial ill

  )oolean a A + alse, true, alse, alse, alse,  alse, true, alse, true, true, alse  1(  int % A ;nte#er.parse;ntar#s60( // num)er o steps  int G A a.len#t( // len#t o re#ister

  int %3P A K( // tap position

  // -imulate operation o sit re#ister.  or int t A 6( t S %( t0 +

  // -imulate one sit5re#ister step.  )oolean next A aG5& T a%3P0( // Compute next )it.

  or int i A G5&( i M 6( i550  ai A ai5&( // -it one position.

  a6 A next( // Put next )it on ri#t end.

  i next0 -ystem.out.print"&"0(  else -ystem.out.print"6"0(

1  -ystem.out.println0(

11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Ji$8Bo'er.java

Below is the syntax highlighted version of :i(2Boxer.java from §1. Arrays.

/*************************************************************************

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 82/180

 * Compilation: javac <icBoxer.java * Execution: java <icBoxer  ** >eads in te ei#t o a %ai ic)oxer, and prints out teir * ic)oxin# cate#ory ly ei#t 5 super eavyei#t0. * * >eerence: ttp://.eliteic)oxin#.com/competitionino8.asp * * $ java <icBoxer &?? * Welter Wei#t * * $ java <icBoxer 866 * -uper Heavy Wei#t * * $ java <icBoxer &&& * Vly Wei#t * * $ java <icBoxer &&9 * -uper Vly Wei#t *

  *************************************************************************/

pu)lic class <icBoxer +  pu)lic static void main-trin# ar#s0 +

int A ;nte#er.parse;ntar#s60(  int ei#ts A + &&9, &&@, &&K, &99, &9, &86, &8@, &?6, &?',  &@?, &6, &', &'?, &K8, &KD, &DK, 96D, DDDD 1(

  -trin# cate#ories A + "Vly Wei#t",  "-uper Vly Wei#t",  "Bantam Wei#t",  "-uper Bantam Wei#t",  "Veater Wei#t",  "-uper Veater Wei#t",  "Li#t Wei#t",  "-uper Li#t Wei#t",  "Welter Wei#t",  "-uper Welter Wei#t",  "iddle Wei#t",  "-uper iddle Wei#t",  "Li#t Heavy Wei#t",  "-uper Li#t Heavy Wei#t",  "Cruiser Wei#t",  "-uper Cruiser Wei#t",  "Heavy Wei#t",  "-uper Heavy Wei#t"

  1(

  or int i A 6( i S ei#ts.len#t( i0 +  i S ei#tsi0 +  -ystem.out.printlncate#oriesi0(  )rea(  1  1  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 83/180

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

6agi$=uare.java

Below is the syntax highlighted version of ?agi(9=uare.java from §1. Arrays.

/************************************************************************* * Compilation: javac a#ic-Fuare.java * Execution: java a#ic-Fuare G * * Jenerates a ma#ic sFuare o order G. 3 ma#ic sFuares is an G5)y5G * matrix o te inte#ers & to GT9, suc tat all ro, column, and * dia#onal sums are eFual. * * ne ay to #enerate a ma#ic sFuare en G is odd is to assi#n * te inte#ers & to GT9 in ascendin# order, startin# at te * )ottom, middle cell. >epeatedly assi#n te next inte#er to te * cell adjacent dia#onally to te ri#t and don. ; tis cell * as already )een assi#ned anoter inte#er, instead use te * cell adjacently a)ove. 2se rap5around to andle )order cases. * ** $ java a#ic-Fuare 8 * ? D 9* 8 @ '

* K & * * $ java a#ic-Fuare @ * && &K 9@ 9 D* &6 &9 &D 9& 8* ? &8 96 99* 98 @ ' &? &* &' 9? & K &@* * Limitations * 55555555555 * 5 G must )e odd *  *************************************************************************/

pu)lic class a#ic-Fuare +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  i G $ 9 AA 60 tro ne >untimeException"G must )e odd"0(

  int ma#ic A ne intGG(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 84/180

  int ro A G5&(  int col A G/9(  ma#icrocol A &(

  or int i A 9( i SA G*G( i0 +  i ma#icro &0 $ Gcol &0 $ G AA 60 +  ro A ro &0 $ G(  col A col &0 $ G(  1  else +  ro A ro 5 & G0 $ G(  // don!t can#e col  1  ma#icrocol A i(  1

  // print results  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  i ma#icij S &60 -ystem.out.print" "0( // or

ali#nment  i ma#icij S &660 -ystem.out.print" "0( // orali#nment  -ystem.out.printma#icij " "0(  1  -ystem.out.println0(  1

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.KipBarGo#er.java

Below is the syntax highlighted version of i#Bar5oder.java from §1. Arrays. 

/************************************************************************* * Compilation: javac ^ipBarCoder.java * Execution: java ^ipBarCoder G ** >eads in a @ di#it Qip code and prints out te postal )arcode. *  *************************************************************************/

pu)lic class ^ipBarCoder +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  int di#its A ne int(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 85/180

  int code A + + &, &, 6, 6, 6 1,  + 6, 6, 6, &, & 1,  + 6, 6, &, 6, & 1,  + 6, 6, &, &, 6 1,  + 6, &, 6, 6, & 1,  + 6, &, 6, &, 6 1,  + 6, &, &, 6, 6 1,  + &, 6, 6, 6, & 1,  + &, 6, 6, &, 6 1,  + &, 6, &, 6, 6 1 1(

  // extract di#its  or int i A &( i SA @( i0 +  di#itsi A G $ &6(  G /A &6(  1

  // compute cec di#it  int cecdi#it A 6(  or int i A &( i SA @( i0

  cecdi#it A di#itsi(  di#its6 A cecdi#it $ &6(

  // print )arcode  -ystem.out.println"*****"0(  or int i A @( i MA 6( i550  or int j A 6( j S @( j0  i codedi#itsij AA &0 -ystem.out.println"*****"0(  else -ystem.out.println"**"0(  -ystem.out.println"*****"0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

)rimeap.java

Below is the syntax highlighted version of rime>a#.java from §1. Arrays. 

/************************************************************************* * Compilation: javac PrimeJap.java * Execution: java 5mxD66B 5msD66B PrimeJap G ** Vind te lon#est consecutive seFuence o inte#ers )eteen 9 and G * it no primes. * * -ample execution: * * $ java 5mxD66B 5msD66B PrimeJap &66

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 86/180

 * %ere are no primes )eteen D6 and D * %at is ' consecutive inte#ers * * $ java 5mxD66B 5msD66B PrimeJap &66666666 * %ere are no primes )eteen ?'89D? and ?'89D&9 * %at is 9&D consecutive inte#ers * *  *************************************************************************/

pu)lic class PrimeJap +  pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  )oolean isprime A ne )ooleanG&(

  or int i A 9( i SA G( i0  isprimei A true(

  // determine primes S G usin# -ieve o Eratostenes  or int i A 9( i*i SA G( i0 +  i isprimei0 +  or int j A i( i*j SA G( j0  isprimei*j A alse(  1  1

  // ind lon#est consecutive seFuence o inte#ers it no primes  int #ap A 6(  int )est#ap A 6(  int ri#t A 6(  or int i A 9( i SA G( i0 +  i isprimei0 #ap A 6(  else #ap(  i #ap M )est#ap0 + )est#ap A #ap( ri#t A i( 1  1

  int let A ri#t 5 )est#ap &(  -ystem.out.println"%ere are no primes )eteen " let " and " ri#t0(  -ystem.out.println"%at is " )est#ap " consecutive inte#ers"0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

ol#!a$h.java

Below is the syntax highlighted version of >old&a(h.java from §1. Arrays. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 87/180

/************************************************************************* * Compilation: javac Jold)ac.java * Execution: java 5mxD66B 5msD66B Jold)ac G ** Computes all primes less tan G and tries to express G as a sum * o to primes. Jold)ac!s conjecture says tat tis is alays* possi)le i G is even and #reater tan 9. Wen G is odd, tese * are called prime pairs.

 * -ample execution: * * $java 5mxD66B 5msD66B Jold)ac &66689D9 * &66689D9 A 8?D &6669D?8 * * $java 5mxD66B 5msD66B Jold)ac &666666& * &666666& is not expressi)le as te sum o to primes * * $java 5mxD66B 5msD66B Jold)ac &666669& * &666669& A 9 &66666&D*

  *************************************************************************/

pu)lic class Jold)ac +  pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  )oolean isprime A ne )ooleanG(

  or int i A 9( i S G( i0  isprimei A true(

  // determine primes S G usin# -ieve o Eratostenes  or int i A 9( i * i S G( i0 +  i isprimei0 +  or int j A i( i * j S G( j0  isprimei*j A alse(  1  1

  // count primes  int primes A 6(  or int i A 9( i S G( i0  i isprimei0 primes(

  -ystem.out.println"=one ta)ulatin# primes."0(

  // store primes in list  int list A ne intprimes(  int n A 6(  or int i A 6( i S G( i0  i isprimei0 listn A i(

  // cec i G can )e expressed as sum o to primes  int let A 6, ri#t A primes5&(  ile let SA ri#t0 +  i listlet listri#t AA G0 )rea(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 88/180

  else i listlet listri#t S G0 let(  else ri#t55(  1  i listlet listri#t AA G0  -ystem.out.printlnG " A " listlet " " listri#t0(  else  -ystem.out.printlnG " not expressi)le as sum o to primes"0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

piral.java

Below is the syntax highlighted version of 9#iral.java from §1. Arrays. 

/************************************************************************* * Compilation: javac -piral.java * Execution: java -piral G ** $ java -piral ? * java -piral ? * & * 9 * 8 * ?

 * K * &9 * & * &@ * &? * &8 * D * @ *  * ' * && * &6 *  *************************************************************************/

pu)lic class -piral +  pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(

  // create G5)y5G array o inte#ers & trou# G  int a A ne intGG(  or int i A 6( i S G( i0

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 89/180

  or int j A 6( j S G( j0  aij A & G*i j(

  // spiral  or int i A G5&, j A 6( i M 6( i55, j0 +  or int A j( S i( 0 -ystem.out.printlnaj0(  or int A j( S i( 0 -ystem.out.printlnai0(  or int A i( M j( 550 -ystem.out.printlnai0(  or int A i( M j( 550 -ystem.out.printlnaj0(  1 

// special case or middle element i G is odd  i G $ 9 AA &0 -ystem.out.printlnaG5&0/9G5&0/90(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011. uler.java

Below is the syntax highlighted version of @uler.java from §1. Arrays.

/************************************************************************* * Compilation: javac Euler.java * Execution: java Euler G *

* %ests eter tere are any ive positive inte#ers tat satisy * aT@ )T@ cT@ dT@ A eT@. ;n &'D Euler conjectured tat no suc * solutions exists, )ut is conjecture as disproved in &D usin# * a computational approac lie te one e tae ere. * * %e pro#ram reads in a command line parameter G and prints out all * solutions it a SA ) SA c SA d SA e SA G. %o speed tin#s up )y * rou#ly a actor o 8 on my system, e precompute an array o * it poers. * * $ java Euler &66 * * $ java Euler &@6 * 9'T@ K?T@ &&6T@ &88T@ A &??T@ // taes a)out 96 seconds * *  *************************************************************************/

pu)lic class Euler +

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 90/180

  // precompute iT@ or i A 6..G  lon# ive A ne lon#G&(  or int i A 6( i SA G( i0  ivei A lon#0 i * i * i * i * i(  -ystem.out.println"=one precomputin# it poers"0(

  // no do exaustive searc  or int e A &( e SA G( e0 +  lon# e@ A ivee(

  // restrict searc to a SA ) SA c SA d SA e  or int a A &( a SA G( a0 +  lon# a@ A ivea(  i a@ a@ a@ a@ M e@0 )rea(

  or int ) A a( ) SA G( )0 +  lon# )@ A ive)(  i a@ )@ )@ )@ M e@0 )rea(

  or int c A )( c SA G( c0 +  lon# c@ A ivec(  i a@ )@ c@ c@ M e@0 )rea(

  or int d A c( d SA G( d0 +  lon# d@ A ived(  i a@ )@ c@ d@ M e@0 )rea(  i a@ )@ c@ d@ AA e@0  -ystem.out.printlna "T@ " ) "T@ " c "T@ " d "T@ A " e "T@"0(

1  1  1  1  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

Bla$8ja$8.java

Below is the syntax highlighted version of Bla(2ja(2.java from §1. Arrays.

/************************************************************************* * Compilation: javac Blacjac.java * Execution: java BlacjacEuler x y Q ** utput te ")asic strate#y" or )lacjac under standard 3tlantic * City rules it decs. 2ses precomputed ta)les.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 91/180

 * * >eerence: ttp://.)lacjacino.com/c#i5)in/)j)se.c#i4#ameAac * * * *  *************************************************************************/

pu)lic class Blacjac +

  pu)lic static void main-trin# ar#s0 +)oolean 7 A true()oolean G A alse(

  )oolean ; A alse( // irrelevant, never used

  int x A ;nte#er.parse;ntar#s60(  int y A ;nte#er.parse;ntar#s&0(  int Q A ;nte#er.parse;ntar#s90(

  // splitij A sould you split it i, i0 i dealer is soin# j

  )oolean split A + + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1,  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,3  + ;, G, 7, 7, 7, 7, 7, 7, G, G, G 1, // 9,9  + ;, G, 7, 7, 7, 7, 7, 7, G, G, G 1, // 8,8  + ;, G, G, G, G, 7, 7, G, G, G, G 1, // ?,?  + ;, G, G, G, G, G, G, G, G, G, G 1, // @,@  + ;, G, 7, 7, 7, 7, 7, G, G, G, G 1, // ,  + ;, G, 7, 7, 7, 7, 7, 7, G, G, G 1, // ','  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // K,K  + ;, G, 7, 7, 7, 7, 7, G, 7, 7, G 1, // D,D  + ;, G, G, G, G, G, G, G, G, G, G 1, // &6,&6  1(

  // sotij A sould you it it 3, i0 i dealer is soin# j  )oolean sot A + + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1,  + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // 3,3

  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,9  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,8  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,?  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,@  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // 3,

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 92/180

  + ;, 7, G, G, G, G, G, G, G, 7, 7 1, // 3,'  + ;, G, G, G, G, G, G, G, G, G, G 1, // 3,K  + ;, G, G, G, G, G, G, G, G, G, G 1, // 3,D  + ;, G, G, G, G, G, G, G, G, G, G 1, // 3,&6  1(

  // sotij A sould you it it total A i i dealer is soin# j  )oolean ard A + + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // 6  + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // &  + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // 9  + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // 8  + ;, ;, ;, ;, ;, ;, ;, ;, ;, ;, ; 1, // ?  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // @  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, //   + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // '  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // K

  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // D  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // &6  + ;, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 1, // &&  + ;, 7, 7, 7, G, G, G, 7, 7, 7, 7 1, // &9  + ;, 7, G, G, G, G, G, 7, 7, 7, 7 1, // &8  + ;, 7, G, G, G, G, G, 7, 7, 7, 7 1, // &?  + ;, 7, G, G, G, G, G, 7, 7, 7, 7 1, // &@  + ;, 7, G, G, G, G, G, 7, 7, 7, 7 1, // &  + ;, G, G, G, G, G, G, G, G, G, G 1, // &'  + ;, G, G, G, G, G, G, G, G, G, G 1, // &K  + ;, G, G, G, G, G, G, G, G, G, G 1, // &D  1(

  // i y is an ace, lip cards  i y AA &0 + y A x( x A &( 1

  // split  i x AA y NN splitxQ0 -ystem.out.println"-plit"0(

  // a sin#le ace  else i x AA &0 +  i sotyQ0 -ystem.out.println"Hit"0(  else -ystem.out.println"-tic"0(  1

  // no ace and did not split  else +

  i ardxyQ0 -ystem.out.println"Hit"0(  else -ystem.out.println"-tic"0(  1

  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 93/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"00"'3 (S) 2011.

)as$al.java

Below is the syntax highlighted version of as(al.java from §1. Arrays. 

/************************************************************************* * Compilation: javac Pascal.java * Execution: java Pascal G ** Computes and prints out Pascal!s trian#le or order G. * ;llustrated ra##ed arrays in Uava. ** $ java Pascal '

 * &* & &* & 9 &* & 8 8 &* & ? ? &* & @ &6 &6 @ &* & &@ 96 &@ &* & ' 9& 8@ 8@ 9& ' &*  *************************************************************************/

pu)lic class Pascal +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  int pascal A ne intG&(

  // initialiQe irst ro  pascal& A ne int& 9(  pascal&& A &(

  // ill in Pascal!s trian#le  or int i A 9( i SA G( i0 +  pascali A ne inti 9(  or int j A &( j S pascali.len#t 5 &( j0  pascalij A pascali5&j5& pascali5&j(  1

  // print results  or int i A &( i SA G( i0 +  or int j A &( j S pascali.len#t 5 &( j0 +  -ystem.out.printpascalij " "0(  1  -ystem.out.println0(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 94/180

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" #ri /!g ' 04"2"'& ($) 2011.

Ran#ome=.java

Below is the syntax highlighted version of andom9e=.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac >andom-eF.java * Execution: java >andom-eF G * * Prints G num)ers )eteen 6 and &. * * $ java >andom-eF @ * 6.&@?'68?8'K'&@ * 6.9&9996689&9?

 * 6.8&'@@@DKK89'? * 6.?&@8DD8@@K?9K8 * 6.?68@9@8&?KK8'& *  *************************************************************************/

pu)lic class >andom-eF +pu)lic static void main-trin# ar#s0 +

  // command5line ar#ument  int G A ;nte#er.parse;ntar#s60(

  // #enerate and print G num)ers )eteen 6 and &  or int i A 6( i S G( i0 +  -ystem.out.printlnat.random00(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

t#In.java

Below is the syntax highlighted version of 9tdIn.java from § 9tandard )i&raries. Here is the

+avado(.

/************************************************************************* * Compilation: javac -td;n.java * Execution: java -td;n interactive test o )asic unctionality0 *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 95/180

 * >eads in data o various types rom standard input. *  *************************************************************************/

import java.util.-canner(import java.util.re#ex.Pattern(

/** * SiM-tandard inputS/iM. %is class provides metods or readin# strin#s * and num)ers rom standard input. -ee* Sa reA"ttp://introcs.cs.princeton.edu/&@inout"M-ection &.@S/aM o * SiM;ntroduction to Pro#rammin# in Uava: 3n ;nterdisciplinary 3pproacS/iM * )y >o)ert -ed#eic and <evin Wayne. * SpM * -ee te tecnical inormation in te documentation o te +\lin ;n1 * class, ic applies to tis class as ell.* * \autor >o)ert -ed#eic * \autor <evin Wayne */

pu)lic inal class -td;n +

  // it doesn!t mae sense to instantiate tis class  private -td;n0 +1

  private static -canner scanner( 

/*** )e#in: section & o 90 o code duplicated rom ;n to -td;n */ 

// assume 2nicode 2%V5K encodin#  private static inal -trin# carsetGame A "2%V5K"(

  // assume lan#ua#e A En#lis, country A 2- or consistency it-ystem.out.  private static inal java.util.Locale usLocale A

ne java.util.Locale"en", "2-"0(

  // te deault toen separator( e maintain te invariant tat tis value// is eld )y te scanner!s delimiter )eteen calls

  private static inal Pattern WH;%E-P3CE[P3%%E>G  A Pattern.compile"ZZp+javaWitespace1"0(

  // maes itespace caracters si#niicantprivate static inal Pattern EP%7[P3%%E>G

  A Pattern.compile""0(

  // used to read te entire input. source:

  // ttp://e)lo#s.java.net/)lo#/pat/arcive/966?/&6/stupid[scanner[&.tml  private static inal Pattern E]E>7%H;GJ[P3%%E>G  A Pattern.compile"ZZ3"0(

  /*** end: section & o 90 o code duplicated rom ;n to -td;n */

  /*** )e#in: section 9 o 90 o code duplicated rom ;n to -td;n,  * it all metods can#ed rom "pu)lic" to "pu)lic static" ***/

  /**

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 96/180

  * ;s te input empty except possi)ly or itespace04 2se tis  * to no eter te next call to +\lin Yread-trin#01,

* +\lin Yread=ou)le01, etc ill succeed.  */  pu)lic static )oolean isEmpty0 +  return Oscanner.asGext0(  1

  /**  * =oes te input ave a next line4 2se tis to no eter te  * next call to +\lin YreadLine01 ill succeed. SpM Vunctionally  * eFuivalent to +\lin YasGextCar01.  */  pu)lic static )oolean asGextLine0 +  return scanner.asGextLine0(  1

  /**  * ;s te input empty includin# itespace04 2se tis to no

* eter te next call to +\lin YreadCar01 ill succeed. SpM

Vunctionally  * eFuivalent to +\lin YasGextLine01.  */  pu)lic static )oolean asGextCar0 +  scanner.use=elimiterEP%7[P3%%E>G0(  )oolean result A scanner.asGext0(  scanner.use=elimiterWH;%E-P3CE[P3%%E>G0(  return result(  1

  /**  * >ead and return te next line.  */  pu)lic static -trin# readLine0 +  -trin# line(  try + line A scanner.nextLine0( 1  catc Exception e0 + line A null( 1  return line(  1

  /**  * >ead and return te next caracter.  */  pu)lic static car readCar0 +  scanner.use=elimiterEP%7[P3%%E>G0(  -trin# c A scanner.next0(

  assert c.len#t0 AA &0 : ";nternal -td0;n.readCar0 errorO"  " Please contact te autors."(  scanner.use=elimiterWH;%E-P3CE[P3%%E>G0(  return c.car3t60(  1

/**  * >ead and return te remainder o te input as a strin#.  */

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 97/180

  pu)lic static -trin# read3ll0 +  i Oscanner.asGextLine00  return ""(

  -trin# result A scanner.use=elimiterE]E>7%H;GJ[P3%%E>G0.next0(  // not tat important to reset delimeter, since no scanner is empty  scanner.use=elimiterWH;%E-P3CE[P3%%E>G0( // )ut let!s do it anyay  return result(  1

  /**  * >ead and return te next strin#.  */  pu)lic static -trin# read-trin#0 +  return scanner.next0(  1

  /**  * >ead and return te next int.

  */  pu)lic static int read;nt0 +  return scanner.next;nt0(  1

  /**  * >ead and return te next dou)le.  */  pu)lic static dou)le read=ou)le0 +  return scanner.next=ou)le0(  1

  /**  * >ead and return te next loat.  */  pu)lic static loat readVloat0 +  return scanner.nextVloat0(  1

  /**  * >ead and return te next lon#.  */  pu)lic static lon# readLon#0 +  return scanner.nextLon#0(  1

  /**

  * >ead and return te next sort.  */  pu)lic static sort read-ort0 +  return scanner.next-ort0(  1

  /**  * >ead and return te next )yte.  */  pu)lic static )yte readByte0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 98/180

  return scanner.nextByte0(  1

  /**  * >ead and return te next )oolean, alloin# case5insensitive  * "true" or "&" or true, and "alse" or "6" or alse.  */  pu)lic static )oolean readBoolean0 +  -trin# s A read-trin#0(  i s.eFuals;#noreCase"true"00 return true(  i s.eFuals;#noreCase"alse"00 return alse(  i s.eFuals"&"00 return true(  i s.eFuals"6"00 return alse(  tro ne java.util.;nputismatcException0(  1

  /**  * >ead all strin#s until te end o input is reaced, and return tem.  */  pu)lic static -trin# read3ll-trin#s0 +

  // e could use read3ll.trim0.split0, )ut tat!s not consistent  // since trim0 uses caracters 6x66..6x96 as itespace  -trin# toens A WH;%E-P3CE[P3%%E>G.splitread3ll00(  i toens.len#t AA 6 toens6.len#t0 M 60  return toens(  -trin# decapitoens A ne -trin#toens.len#t5&(  or int iA6( i S toens.len#t5&( i0  decapitoensi A toensi&(  return decapitoens(  1

  /**  * >ead all ints until te end o input is reaced, and return tem.  */  pu)lic static int read3ll;nts0 +  -trin# ields A read3ll-trin#s0(  int vals A ne intields.len#t(  or int i A 6( i S ields.len#t( i0  valsi A ;nte#er.parse;ntieldsi0(  return vals(  1

  /**  * >ead all dou)les until te end o input is reaced, and return tem.  */  pu)lic static dou)le read3ll=ou)les0 +  -trin# ields A read3ll-trin#s0(

  dou)le vals A ne dou)leields.len#t(  or int i A 6( i S ields.len#t( i0  valsi A =ou)le.parse=ou)leieldsi0(  return vals(  1 

/*** end: section 9 o 90 o code duplicated rom ;n to -td;n */ 

/**

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 99/180

  * ; -td;n can#es, use tis to reinitialiQe te scanner.  */  private static void resync0 +  set-cannerne -cannerne java.io.Buered;nput-tream-ystem.in0,

carsetGame00(  1 

private static void set-canner-canner scanner0 +  -td;n.scanner A scanner(  -td;n.scanner.useLocaleusLocale0(  1

  // do tis once en -td;n is initialiQed  static +  resync0(  1

  /**  * >eads all ints rom stdin.  * \deprecated Vor more consistency, use +\lin Yread3ll;nts01

  */  pu)lic static int read;nts0 +  return read3ll;nts0(  1

  /**  * >eads all dou)les rom stdin.  * \deprecated Vor more consistency, use +\lin Yread3ll=ou)les01  */  pu)lic static dou)le read=ou)les0 +  return read3ll=ou)les0(  1

  /**  * >eads all -trin#s rom stdin.  * \deprecated Vor more consistency, use +\lin Yread3ll-trin#s01  */  pu)lic static -trin# read-trin#s0 +  return read3ll-trin#s0(  1

  /**  * ;nteractive test o )asic unctionality.  */  pu)lic static void main-trin# ar#s0 +

  -ystem.out.println"%ype a strin#: "0(  -trin# s A -td;n.read-trin#0(  -ystem.out.println"7our strin# as: " s0(  -ystem.out.println0(

  -ystem.out.println"%ype an int: "0(  int a A -td;n.read;nt0(  -ystem.out.println"7our int as: " a0(  -ystem.out.println0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 100/180

  -ystem.out.println"%ype a )oolean: "0(  )oolean ) A -td;n.readBoolean0(  -ystem.out.println"7our )oolean as: " )0(  -ystem.out.println0(

  -ystem.out.println"%ype a dou)le: "0(  dou)le c A -td;n.read=ou)le0(  -ystem.out.println"7our dou)le as: " c0(  -ystem.out.println0(

  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )!e Sep 1% 14"23"2+ ($) 201.

t#ut.java

Below is the syntax highlighted version of 9td%ut.java from § 9tandard )i&raries. Here is the

+avado(.

/************************************************************************* * Compilation: javac -tdut.java * Execution: java -tdut * * Writes data o various types to standard output. *  *************************************************************************/

import java.io.utput-treamWriter(import java.io.PrintWriter(import java.io.2nsupportedEncodin#Exception(import java.util.Locale(

/** * SiM-tandard outputS/iM. %is class provides metods or ritin# strin#s * and num)ers to standard output. * SpM * Vor additional documentation, see SareA"ttp://introcs.cs.princeton.edu/&@inout"M-ection &.@S/aM o

 * SiM;ntroduction to Pro#rammin# in Uava: 3n ;nterdisciplinary 3pproacS/iM)y >o)ert -ed#eic and <evin Wayne. * * \autor >o)ert -ed#eic * \autor <evin Wayne */pu)lic inal class -tdut +

  // orce 2nicode 2%V5K encodin#( oterise it!s system dependent  private static inal -trin# carsetGame A "2%V5K"(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 101/180

  // assume lan#ua#e A En#lis, country A 2- or consistency it -td;n  private static inal Locale 2-[LC3LE A ne Locale"en", "2-"0(

  // send output ere  private static PrintWriter out(

  // tis is called )eore invoin# any metods  static +  try +  out A ne PrintWriterne utput-treamWriter-ystem.out,carsetGame0, true0(  1  catc 2nsupportedEncodin#Exception e0 + -ystem.out.printlne0( 1  1

  // don!t instantiate  private -tdut0 + 1

  // close te output stream not reFuired0

  /**  * Close standard output.  */  pu)lic static void close0 +  out.close0(  1

  /**  * %erminate te current line )y printin# te line separator strin#.  */  pu)lic static void println0 +  out.println0(  1

  /**  * Print an o)ject to standard output and ten terminate te line.  */  pu)lic static void println)ject x0 +  out.printlnx0(  1

  /**  * Print a )oolean to standard output and ten terminate te line.  */  pu)lic static void println)oolean x0 +  out.printlnx0(  1

  /**  * Print a car to standard output and ten terminate te line.  */  pu)lic static void printlncar x0 +  out.printlnx0(  1

  /**  * Print a dou)le to standard output and ten terminate te line.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 102/180

  */  pu)lic static void printlndou)le x0 +  out.printlnx0(  1

  /**  * Print a loat to standard output and ten terminate te line.  */  pu)lic static void printlnloat x0 +  out.printlnx0(  1

  /**  * Print an int to standard output and ten terminate te line.  */  pu)lic static void printlnint x0 +  out.printlnx0(  1

  /**

  * Print a lon# to standard output and ten terminate te line.  */  pu)lic static void printlnlon# x0 +  out.printlnx0(  1

  /**  * Print a sort to standard output and ten terminate te line.  */  pu)lic static void printlnsort x0 +  out.printlnx0(  1

  /**  * Print a )yte to standard output and ten terminate te line.  */  pu)lic static void println)yte x0 +  out.printlnx0(  1

  /**  * Vlus standard output.  */  pu)lic static void print0 +  out.lus0(  1

  /**  * Print an )ject to standard output and lus standard output.  */  pu)lic static void print)ject x0 +  out.printx0(  out.lus0(  1

  /**  * Print a )oolean to standard output and lus standard output.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 103/180

  */  pu)lic static void print)oolean x0 +  out.printx0(  out.lus0(  1

  /**  * Print a car to standard output and lus standard output.  */  pu)lic static void printcar x0 +  out.printx0(  out.lus0(  1

  /**  * Print a dou)le to standard output and lus standard output.  */  pu)lic static void printdou)le x0 +  out.printx0(  out.lus0(

  1

  /**  * Print a loat to standard output and lus standard output.  */  pu)lic static void printloat x0 +  out.printx0(  out.lus0(  1

  /**  * Print an int to standard output and lus standard output.  */  pu)lic static void printint x0 +  out.printx0(  out.lus0(  1

  /**  * Print a lon# to standard output and lus standard output.  */  pu)lic static void printlon# x0 +  out.printx0(  out.lus0(  1

  /**

  * Print a sort to standard output and lus standard output.  */  pu)lic static void printsort x0 +  out.printx0(  out.lus0(  1

  /**  * Print a )yte to standard output and lus standard output.  */

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 104/180

  pu)lic static void print)yte x0 +  out.printx0(  out.lus0(  1

  /**  * Print a ormatted strin# to standard output usin# te speciied  * ormat strin# and ar#uments, and lus standard output.  */  pu)lic static void print-trin# ormat, )ject... ar#s0 +  out.print2-[LC3LE, ormat, ar#s0(  out.lus0(  1

  /**  * Print a ormatted strin# to standard output usin# te speciied  * locale, ormat strin#, and ar#uments, and lus standard output.  */  pu)lic static void printLocale locale, -trin# ormat, )ject... ar#s0 +  out.printlocale, ormat, ar#s0(

  out.lus0(  1

  // %is metod is just ere to test te class  pu)lic static void main-trin# ar#s0 +

  // rite to stdout  -tdut.println"%est"0(  -tdut.println&'0(  -tdut.printlntrue0(  -tdut.print"$.Zn", &.6/'.60(  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" )!e Sep 1% 14"23"2+ ($) 201.

t#Dra,.java

Below is the syntax highlighted version of 9td$raw.java from § 9tandard )i&raries. Here is the

+avado(.

/************************************************************************* * Compilation: javac -td=ra.java * Execution: java -td=ra * * -tandard drain# li)rary. %is class provides a )asic capa)ility or * creatin# drain#s it your pro#rams. ;t uses a simple #rapics model tat * allos you to create drain#s consistin# o points, lines, and curves * in a indo on your computer and to save te drain#s to a ile.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 105/180

 * * %odo * 5555 * 5 3dd support or #radient ill, etc. * 5 Vix setCanvas-iQe0 so tat it can only )e called once. * * >emars * 5555555 * 5 don!t use 3ine%ransorm or rescalin# since it inverts * ima#es and strin#s * 5 careul usin# setVont in inner loop itin an animation 5 * it can cause licer *  *************************************************************************/

import java.at.*(import java.at.event.*(import java.at.#eom.*(import java.at.ima#e.*(import java.io.*(

import java.net.*(import java.util.LinedList(import java.util.%ree-et(import javax.ima#eio.;ma#e;(import javax.sin#.*(

/** * SiM-tandard draS/iM. %is class provides a )asic capa)ility or * creatin# drain#s it your pro#rams. ;t uses a simple #rapics model tat * allos you to create drain#s consistin# o points, lines, and curves * in a indo on your computer and to save te drain#s to a ile. * SpM * Vor additional documentation, see SareA"ttp://introcs.cs.princeton.edu/&@inout"M-ection &.@S/aM o * SiM;ntroduction to Pro#rammin# in Uava: 3n ;nterdisciplinary 3pproacS/iM)y >o)ert -ed#eic and <evin Wayne. * * \autor >o)ert -ed#eic * \autor <evin Wayne */pu)lic inal class -td=ra implements 3ctionListener, ouseListener,ouseotionListener, <eyListener +

  // pre5deined colors  pu)lic static inal Color BL3C< A Color.BL3C<(  pu)lic static inal Color BL2E A Color.BL2E(  pu)lic static inal Color C73G A Color.C73G(

  pu)lic static inal Color =3><[J>37 A Color.=3><[J>37(  pu)lic static inal Color J>37 A Color.J>37(  pu)lic static inal Color J>EEG A Color.J>EEG(  pu)lic static inal Color L;JH%[J>37 A Color.L;JH%[J>37(  pu)lic static inal Color 3JEG%3 A Color.3JEG%3(  pu)lic static inal Color >3GJE A Color.>3GJE(  pu)lic static inal Color P;G< A Color.P;G<(  pu)lic static inal Color >E= A Color.>E=(  pu)lic static inal Color WH;%E A Color.WH;%E(  pu)lic static inal Color 7ELLW A Color.7ELLW(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 106/180

  /**  * -ade o )lue used in ;ntroduction to Pro#rammin# in Uava.  * ;t is Pantone 8662. %e >JB values are approximately D, D6, &0.  */  pu)lic static inal Color B<[BL2E A ne Color D, D6, &0(  pu)lic static inal Color B<[L;JH%[BL2E A ne Color&68, &DK, 9?80(

  /**  * -ade o red used in 3l#oritms ?t edition.  * ;t is Pantone &K6@2. %e >JB values are approximately &@6, 8@, 8&0.  */  pu)lic static inal Color B<[>E= A ne Color&@6, 8@, 8&0(

  // deault colors  private static inal Color =EV32L%[PEG[CL> A BL3C<(  private static inal Color =EV32L%[CLE3>[CL> A WH;%E(

  // current pen color  private static Color penColor(

  // deault canvas siQe is =EV32L%[-;^E5)y5=EV32L%[-;^E  private static inal int =EV32L%[-;^E A @&9(  private static int idt A =EV32L%[-;^E(  private static int ei#t A =EV32L%[-;^E(

  // deault pen radius  private static inal dou)le =EV32L%[PEG[>3=;2- A 6.669(

  // current pen radius  private static dou)le pen>adius(

  // so e dra immediately or ait until next so4  private static )oolean deer A alse(

  // )oundary o drain# canvas, @$ )order  private static inal dou)le B>=E> A 6.6@(  private static inal dou)le =EV32L%[;G A 6.6(  private static inal dou)le =EV32L%[3 A &.6(  private static inal dou)le =EV32L%[7;G A 6.6(  private static inal dou)le =EV32L%[73 A &.6(  private static dou)le xmin, ymin, xmax, ymax(

  // or syncroniQation  private static )ject mouseLoc A ne )ject0(  private static )ject eyLoc A ne )ject0(

  // deault ont  private static inal Vont =EV32L%[VG% A ne Vont"-ans-eri", Vont.PL3;G,&0(

  // current ont  private static Vont ont(

  // dou)le )uered #rapics  private static Buered;ma#e oscreen;ma#e, onscreen;ma#e(  private static Jrapics9= oscreen, onscreen(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 107/180

  // sin#leton or call)acs: avoids #eneration o extra .class iles  private static -td=ra std A ne -td=ra0(

  // te rame or drain# to te screen  private static UVrame rame(

  // mouse state  private static )oolean mousePressed A alse(  private static dou)le mouse A 6(  private static dou)le mouse7 A 6(

  // Fueue o typed ey caracters  private static LinedListSCaracterM eys%yped A neLinedListSCaracterM0(

  // set o ey codes currently pressed don  private static %ree-etS;nte#erM eys=on A ne %ree-etS;nte#erM0( 

// sin#leton pattern: client can!t instantiate  private -td=ra0 + 1

  // static initialiQer  static + init0( 1

  /**  * -et te indo siQe to te deault siQe @&95)y5@&9 pixels.  * %is metod must )e called )eore any oter commands.  */  pu)lic static void setCanvas-iQe0 +  setCanvas-iQe=EV32L%[-;^E, =EV32L%[-;^E0(  1

  /**  * -et te indo siQe to 5)y5 pixels.  * %is metod must )e called )eore any oter commands.  *  * \param te idt as a num)er o pixels  * \param te ei#t as a num)er o pixels  * \tros a ;lle#al3r#umentException i te idt or ei#t is 6 orne#ative  */  pu)lic static void setCanvas-iQeint , int 0 +  i S & S &0 tro ne ;lle#al3r#umentException"idt andei#t must )e positive"0(

  idt A (  ei#t A (  init0(  1

  // init  private static void init0 +  i rame OA null0 rame.set]isi)lealse0(  rame A ne UVrame0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 108/180

  oscreen;ma#e A ne Buered;ma#eidt, ei#t,Buered;ma#e.%7PE[;G%[3>JB0(  onscreen;ma#e A ne Buered;ma#eidt, ei#t,Buered;ma#e.%7PE[;G%[3>JB0(  oscreen A oscreen;ma#e.createJrapics0(  onscreen A onscreen;ma#e.createJrapics0(  setscale0(  set7scale0(  oscreen.setColor=EV32L%[CLE3>[CL>0(  oscreen.ill>ect6, 6, idt, ei#t0(  setPenColor0(  setPen>adius0(  setVont0(  clear0(

  // add antialiasin#  >enderin#Hints ints A ne>enderin#Hints>enderin#Hints.<E7[3G%;3L;3-;GJ, >enderin#Hints.]3L2E[3G%;3L;3-[G0(

  ints.put>enderin#Hints.<E7[>EG=E>;GJ,>enderin#Hints.]3L2E[>EG=E>[I23L;%70(  oscreen.add>enderin#Hintsints0(

  // rame stu  ;ma#e;con icon A ne ;ma#e;cononscreen;ma#e0(  ULa)el dra A ne ULa)elicon0(

  dra.addouseListenerstd0(  dra.addouseotionListenerstd0(

  rame.setContentPanedra0(  rame.add<eyListenerstd0( // ULa)el cannot #et ey)oard ocus  rame.set>esiQa)lealse0(  rame.set=eaultCloseperationUVrame.E;%[G[CL-E0( //closes all indos  // rame.set=eaultCloseperationUVrame.=;-P-E[G[CL-E0( //closes only current indo  rame.set%itle"-tandard =ra"0(  rame.setUenuBarcreateenuBar00(  rame.pac0(  rame.reFuestVocus;nWindo0(  rame.set]isi)letrue0(  1

  // create te menu )ar can#ed to private0  private static UenuBar createenuBar0 +

  UenuBar menuBar A ne UenuBar0(  Uenu menu A ne Uenu"Vile"0(  menuBar.addmenu0(  Uenu;tem menu;tem& A ne Uenu;tem" -ave... "0(  menu;tem&.add3ctionListenerstd0(  menu;tem&.set3ccelerator<ey-troe.#et<ey-troe<eyEvent.]<[-, %oolit.#et=eault%oolit0.#etenu-ortcut<eyas000(  menu.addmenu;tem&0(  return menuBar(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 109/180

  1

  /*************************************************************************  * 2ser and screen coordinate systems  *************************************************************************/

  /**  * -et te x5scale to )e te deault )eteen 6.6 and &.60.  */  pu)lic static void setscale0 + setscale=EV32L%[;G, =EV32L%[30( 1

  /**  * -et te y5scale to )e te deault )eteen 6.6 and &.60.  */  pu)lic static void set7scale0 + set7scale=EV32L%[7;G, =EV32L%[730( 1

  /**  * -et te x5scale a &6$ )order is added to te values0  * \param min te minimum value o te x5scale

  * \param max te maximum value o te x5scale  */  pu)lic static void setscaledou)le min, dou)le max0 +  dou)le siQe A max 5 min(  syncroniQed mouseLoc0 +  xmin A min 5 B>=E> * siQe(  xmax A max B>=E> * siQe(  1  1

  /**  * -et te y5scale a &6$ )order is added to te values0.  * \param min te minimum value o te y5scale  * \param max te maximum value o te y5scale  */  pu)lic static void set7scaledou)le min, dou)le max0 +  dou)le siQe A max 5 min(  syncroniQed mouseLoc0 +  ymin A min 5 B>=E> * siQe(  ymax A max B>=E> * siQe(  1  1

  /**  * -et te x5scale and y5scale a &6$ )order is added to te values0  * \param min te minimum value o te x5 and y5scales  * \param max te maximum value o te x5 and y5scales

  */  pu)lic static void set-caledou)le min, dou)le max0 +  dou)le siQe A max 5 min(  syncroniQed mouseLoc0 +  xmin A min 5 B>=E> * siQe(  xmax A max B>=E> * siQe(  ymin A min 5 B>=E> * siQe(  ymax A max B>=E> * siQe(  1  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 110/180

  // elper unctions tat scale rom user coordinates to screen coordinatesand )ac  private static dou)le scaledou)le x0 + return idt * x 5 xmin0 /xmax 5 xmin0( 1  private static dou)le scale7dou)le y0 + return ei#t * ymax 5 y0 /ymax 5 ymin0( 1  private static dou)le actordou)le 0 + return * idt /at.a)sxmax 5 xmin0( 1  private static dou)le actor7dou)le 0 + return * ei#t /at.a)symax 5 ymin0( 1  private static dou)le userdou)le x0 + return xmin x * xmax 5 xmin0/ idt( 1  private static dou)le user7dou)le y0 + return ymax 5 y * ymax 5 ymin0/ ei#t( 1

  /**  * Clear te screen to te deault color ite0.  */

  pu)lic static void clear0 + clear=EV32L%[CLE3>[CL>0( 1  /**  * Clear te screen to te #iven color.  * \param color te Color to mae te )ac#round  */  pu)lic static void clearColor color0 +  oscreen.setColorcolor0(  oscreen.ill>ect6, 6, idt, ei#t0(  oscreen.setColorpenColor0(  dra0(  1

  /**  * Jet te current pen radius.  */  pu)lic static dou)le #etPen>adius0 + return pen>adius( 1

  /**  * -et te pen siQe to te deault .6690.  */  pu)lic static void setPen>adius0 + setPen>adius=EV32L%[PEG[>3=;2-0( 1  /**  * -et te radius o te pen to te #iven siQe.  * \param r te radius o te pen  * \tros ;lle#al3r#umentException i r is ne#ative  */  pu)lic static void setPen>adiusdou)le r0 +

  i r S 60 tro ne ;lle#al3r#umentException"pen radius must )enonne#ative"0(  pen>adius A r(  loat scaledPen>adius A loat0 r * =EV32L%[-;^E0(  Basic-troe stroe A ne Basic-troescaledPen>adius,Basic-troe.C3P[>2G=, Basic-troe.U;G[>2G=0(  // Basic-troe stroe A ne Basic-troescaledPen>adius0(  oscreen.set-troestroe0(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 111/180

  /**  * Jet te current pen color.  */  pu)lic static Color #etPenColor0 + return penColor( 1

  /**  * -et te pen color to te deault color )lac0.  */  pu)lic static void setPenColor0 + setPenColor=EV32L%[PEG[CL>0( 1

  /**  * -et te pen color to te #iven color. %e availa)le pen colors are  * BL3C<, BL2E, C73G, =3><[J>37, J>37, J>EEG, L;JH%[J>37, 3JEG%3,  * >3GJE, P;G<, >E=, WH;%E, and 7ELLW.  * \param color te Color to mae te pen  */  pu)lic static void setPenColorColor color0 +  penColor A color(  oscreen.setColorpenColor0(  1

  /**  * -et te pen color to te #iven >JB color.  * \param red te amount o red )eteen 6 and 9@@0  * \param #reen te amount o #reen )eteen 6 and 9@@0  * \param )lue te amount o )lue )eteen 6 and 9@@0  * \tros ;lle#al3r#umentException i te amount o red, #reen, or )lueare outside prescri)ed ran#e  */  pu)lic static void setPenColorint red, int #reen, int )lue0 +  i red S 6 red MA 9@0 tro ne;lle#al3r#umentException"amount o red must )e )eteen 6 and 9@@"0(  i #reen S 6 #reen MA 9@0 tro ne;lle#al3r#umentException"amount o red must )e )eteen 6 and 9@@"0(  i )lue S 6 )lue MA 9@0 tro ne;lle#al3r#umentException"amount o red must )e )eteen 6 and 9@@"0(  setPenColorne Colorred, #reen, )lue00(  1

  /**  * Jet te current ont.  */  pu)lic static Vont #etVont0 + return ont( 1

  /**  * -et te ont to te deault ont sans seri, & point0.  */

  pu)lic static void setVont0 + setVont=EV32L%[VG%0( 1

  /**  * -et te ont to te #iven value.  * \param te ont to mae text  */  pu)lic static void setVontVont 0 + ont A ( 1

  /*************************************************************************

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 112/180

  * =rain# #eometric sapes.  *************************************************************************/

  /**  * =ra a line rom x6, y60 to x&, y&0.  * \param x6 te x5coordinate o te startin# point  * \param y6 te y5coordinate o te startin# point  * \param x& te x5coordinate o te destination point  * \param y& te y5coordinate o te destination point  */  pu)lic static void linedou)le x6, dou)le y6, dou)le x&, dou)le y&0 +  oscreen.drane Line9=.=ou)lescalex60, scale7y60, scalex&0,scale7y&000(  dra0(  1

  /**  * =ra one pixel at x, y0.  * \param x te x5coordinate o te pixel  * \param y te y5coordinate o te pixel

  */  private static void pixeldou)le x, dou)le y0 +  oscreen.ill>ectint0 at.roundscalex00, int0at.roundscale7y00, &, &0(  1

  /**  * =ra a point at x, y0.  * \param x te x5coordinate o te point  * \param y te y5coordinate o te point  */  pu)lic static void pointdou)le x, dou)le y0 +  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le r A pen>adius(  loat scaledPen>adius A loat0 r * =EV32L%[-;^E0(

  // dou)le s A actor9*r0(  // dou)le s A actor79*r0(  // i s SA & NN s SA &0 pixelx, y0(  i scaledPen>adius SA &0 pixelx, y0(  else oscreen.illne Ellipse9=.=ou)lexs 5 scaledPen>adius/9, ys 5scaledPen>adius/9,  scaledPen>adius,scaledPen>adius00(  dra0(  1

  /**  * =ra a circle o radius r, centered on x, y0.  * \param x te x5coordinate o te center o te circle  * \param y te y5coordinate o te center o te circle  * \param r te radius o te circle  * \tros ;lle#al3r#umentException i te radius o te circle isne#ative  */  pu)lic static void circledou)le x, dou)le y, dou)le r0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 113/180

  i r S 60 tro ne ;lle#al3r#umentException"circle radius must )enonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*r0(  dou)le s A actor79*r0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.drane Ellipse9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra illed circle o radius r, centered on x, y0.  * \param x te x5coordinate o te center o te circle  * \param y te y5coordinate o te center o te circle  * \param r te radius o te circle  * \tros ;lle#al3r#umentException i te radius o te circle isne#ative  */

  pu)lic static void illedCircledou)le x, dou)le y, dou)le r0 +  i r S 60 tro ne ;lle#al3r#umentException"circle radius must )enonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*r0(  dou)le s A actor79*r0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.illne Ellipse9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra an ellipse it #iven semimajor and semiminor axes, centered onx, y0.  * \param x te x5coordinate o te center o te ellipse  * \param y te y5coordinate o te center o te ellipse  * \param semiajor3xis is te semimajor axis o te ellipse  * \param semiinor3xis is te semiminor axis o te ellipse  * \tros ;lle#al3r#umentException i eiter o te axes are ne#ative  */  pu)lic static void ellipsedou)le x, dou)le y, dou)le semiajor3xis,dou)le semiinor3xis0 +  i semiajor3xis S 60 tro ne ;lle#al3r#umentException"ellipsesemimajor axis must )e nonne#ative"0(

  i semiinor3xis S 60 tro ne ;lle#al3r#umentException"ellipsesemiminor axis must )e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*semiajor3xis0(  dou)le s A actor79*semiinor3xis0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.drane Ellipse9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 114/180

  1

  /**  * =ra an ellipse it #iven semimajor and semiminor axes, centered onx, y0.  * \param x te x5coordinate o te center o te ellipse  * \param y te y5coordinate o te center o te ellipse  * \param semiajor3xis is te semimajor axis o te ellipse  * \param semiinor3xis is te semiminor axis o te ellipse  * \tros ;lle#al3r#umentException i eiter o te axes are ne#ative  */  pu)lic static void illedEllipsedou)le x, dou)le y, dou)le semiajor3xis,dou)le semiinor3xis0 +  i semiajor3xis S 60 tro ne ;lle#al3r#umentException"ellipsesemimajor axis must )e nonne#ative"0(  i semiinor3xis S 60 tro ne ;lle#al3r#umentException"ellipsesemiminor axis must )e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*semiajor3xis0(

  dou)le s A actor79*semiinor3xis0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.illne Ellipse9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra an arc o radius r, centered on x, y0, rom an#le& to an#le9 inde#rees0.  * \param x te x5coordinate o te center o te circle  * \param y te y5coordinate o te center o te circle  * \param r te radius o te circle  * \param an#le& te startin# an#le. 6 ould mean an arc )e#innin# at 8o!cloc.  * \param an#le9 te an#le at te end o te arc. Vor example, i  * you ant a D6 de#ree arc, ten an#le9 sould )e an#le& D6.  * \tros ;lle#al3r#umentException i te radius o te circle isne#ative  */  pu)lic static void arcdou)le x, dou)le y, dou)le r, dou)le an#le&, dou)lean#le90 +  i r S 60 tro ne ;lle#al3r#umentException"arc radius must )enonne#ative"0(  ile an#le9 S an#le&0 an#le9 A 86(  dou)le xs A scalex0(

  dou)le ys A scale7y0(  dou)le s A actor9*r0(  dou)le s A actor79*r0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.drane 3rc9=.=ou)lexs 5 s/9, ys 5 s/9, s, s,an#le&, an#le9 5 an#le&, 3rc9=.PEG00(  dra0(  1

  /**

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 115/180

  * =ra a sFuare o side len#t 9r, centered on x, y0.  * \param x te x5coordinate o te center o te sFuare  * \param y te y5coordinate o te center o te sFuare  * \param r radius is al te len#t o any side o te sFuare  * \tros ;lle#al3r#umentException i r is ne#ative  */  pu)lic static void sFuaredou)le x, dou)le y, dou)le r0 +  i r S 60 tro ne ;lle#al3r#umentException"sFuare side len#t must)e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*r0(  dou)le s A actor79*r0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.drane >ectan#le9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**

  * =ra a illed sFuare o side len#t 9r, centered on x, y0.  * \param x te x5coordinate o te center o te sFuare  * \param y te y5coordinate o te center o te sFuare  * \param r radius is al te len#t o any side o te sFuare  * \tros ;lle#al3r#umentException i r is ne#ative  */  pu)lic static void illed-Fuaredou)le x, dou)le y, dou)le r0 +  i r S 60 tro ne ;lle#al3r#umentException"sFuare side len#t must)e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*r0(  dou)le s A actor79*r0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.illne >ectan#le9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra a rectan#le o #iven al idt and al ei#t, centered on x,y0.  * \param x te x5coordinate o te center o te rectan#le  * \param y te y5coordinate o te center o te rectan#le  * \param alWidt is al te idt o te rectan#le  * \param alHei#t is al te ei#t o te rectan#le

  * \tros ;lle#al3r#umentException i alWidt or alHei#t is ne#ative  */  pu)lic static void rectan#ledou)le x, dou)le y, dou)le alWidt, dou)lealHei#t0 +  i alWidt S 60 tro ne ;lle#al3r#umentException"al idtmust )e nonne#ative"0(  i alHei#t S 60 tro ne ;lle#al3r#umentException"al ei#tmust )e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 116/180

  dou)le s A actor9*alWidt0(  dou)le s A actor79*alHei#t0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.drane >ectan#le9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra a illed rectan#le o #iven al idt and al ei#t, centeredon x, y0.  * \param x te x5coordinate o te center o te rectan#le  * \param y te y5coordinate o te center o te rectan#le  * \param alWidt is al te idt o te rectan#le  * \param alHei#t is al te ei#t o te rectan#le  * \tros ;lle#al3r#umentException i alWidt or alHei#t is ne#ative  */  pu)lic static void illed>ectan#ledou)le x, dou)le y, dou)le alWidt,dou)le alHei#t0 +  i alWidt S 60 tro ne ;lle#al3r#umentException"al idt

must )e nonne#ative"0(  i alHei#t S 60 tro ne ;lle#al3r#umentException"al ei#tmust )e nonne#ative"0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor9*alWidt0(  dou)le s A actor79*alHei#t0(  i s SA & NN s SA &0 pixelx, y0(  else oscreen.illne >ectan#le9=.=ou)lexs 5 s/9, ys 5 s/9, s,s00(  dra0(  1

  /**  * =ra a poly#on it te #iven xi, yi0 coordinates.  * \param x an array o all te x5coordindates o te poly#on  * \param y an array o all te y5coordindates o te poly#on  */  pu)lic static void poly#ondou)le x, dou)le y0 +  int G A x.len#t(  JeneralPat pat A ne JeneralPat0(  pat.move%oloat0 scalex60, loat0 scale7y600(  or int i A 6( i S G( i0  pat.line%oloat0 scalexi0, loat0 scale7yi00(  pat.closePat0(  oscreen.drapat0(

  dra0(  1

  /**  * =ra a illed poly#on it te #iven xi, yi0 coordinates.  * \param x an array o all te x5coordindates o te poly#on  * \param y an array o all te y5coordindates o te poly#on  */  pu)lic static void illedPoly#ondou)le x, dou)le y0 +  int G A x.len#t(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 117/180

  JeneralPat pat A ne JeneralPat0(  pat.move%oloat0 scalex60, loat0 scale7y600(  or int i A 6( i S G( i0  pat.line%oloat0 scalexi0, loat0 scale7yi00(  pat.closePat0(  oscreen.illpat0(  dra0(  1

  /*************************************************************************  * =rain# ima#es.  *************************************************************************/

  // #et an ima#e rom te #iven ilename  private static ;ma#e #et;ma#e-trin# ilename0 +

  // to read rom ile  ;ma#e;con icon A ne ;ma#e;conilename0(

  // try to read rom 2>L  i icon AA null0 icon.#et;ma#eLoad-tatus0 OAedia%racer.CPLE%E00 +  try +  2>L url A ne 2>Lilename0(  icon A ne ;ma#e;conurl0(  1 catc Exception e0 + /* not a url */ 1  1

  // in case ile is inside a .jar  i icon AA null0 icon.#et;ma#eLoad-tatus0 OAedia%racer.CPLE%E00 +  2>L url A -td=ra.class.#et>esourceilename0(  i url AA null0 tro ne ;lle#al3r#umentException"ima#e " ilename " not ound"0(  icon A ne ;ma#e;conurl0(  1

  return icon.#et;ma#e0(  1

  /**  * =ra picture #i, jp#, or pn#0 centered on x, y0.  * \param x te center x5coordinate o te ima#e  * \param y te center y5coordinate o te ima#e  * \param s te name o te ima#e/picture, e.#., ")all.#i"

  * \tros ;lle#al3r#umentException i te ima#e is corrupt  */  pu)lic static void picturedou)le x, dou)le y, -trin# s0 +  ;ma#e ima#e A #et;ma#es0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  int s A ima#e.#etWidtnull0(  int s A ima#e.#etHei#tnull0(  i s S 6 s S 60 tro ne ;lle#al3r#umentException"ima#e " s " is corrupt"0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 118/180

  oscreen.dra;ma#eima#e, int0 at.roundxs 5 s/9.60, int0at.roundys 5 s/9.60, null0(  dra0(  1

  /**  * =ra picture #i, jp#, or pn#0 centered on x, y0,  * rotated #iven num)er o de#rees  * \param x te center x5coordinate o te ima#e  * \param y te center y5coordinate o te ima#e  * \param s te name o te ima#e/picture, e.#., ")all.#i"  * \param de#rees is te num)er o de#rees to rotate counterclocise  * \tros ;lle#al3r#umentException i te ima#e is corrupt  */  pu)lic static void picturedou)le x, dou)le y, -trin# s, dou)le de#rees0 +  ;ma#e ima#e A #et;ma#es0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  int s A ima#e.#etWidtnull0(

  int s A ima#e.#etHei#tnull0(  i s S 6 s S 60 tro ne ;lle#al3r#umentException"ima#e " s " is corrupt"0(

  oscreen.rotateat.to>adians5de#rees0, xs, ys0(  oscreen.dra;ma#eima#e, int0 at.roundxs 5 s/9.60, int0at.roundys 5 s/9.60, null0(  oscreen.rotateat.to>adiansde#rees0, xs, ys0(

  dra0(  1

  /**  * =ra picture #i, jp#, or pn#0 centered on x, y0, rescaled to 5)y5.  * \param x te center x coordinate o te ima#e  * \param y te center y coordinate o te ima#e  * \param s te name o te ima#e/picture, e.#., ")all.#i"  * \param te idt o te ima#e  * \param te ei#t o te ima#e  * \tros ;lle#al3r#umentException i te idt ei#t are ne#ative  * \tros ;lle#al3r#umentException i te ima#e is corrupt  */  pu)lic static void picturedou)le x, dou)le y, -trin# s, dou)le , dou)le0 +  ;ma#e ima#e A #et;ma#es0(  dou)le xs A scalex0(  dou)le ys A scale7y0(

  i S 60 tro ne ;lle#al3r#umentException"idt is ne#ative: " 0(  i S 60 tro ne ;lle#al3r#umentException"ei#t is ne#ative: " 0(  dou)le s A actor0(  dou)le s A actor70(  i s S 6 s S 60 tro ne ;lle#al3r#umentException"ima#e " s " is corrupt"0(  i s SA & NN s SA &0 pixelx, y0(  else +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 119/180

  oscreen.dra;ma#eima#e, int0 at.roundxs 5 s/9.60,  int0 at.roundys 5 s/9.60,  int0 at.rounds0,  int0 at.rounds0, null0(  1  dra0(  1

  /**  * =ra picture #i, jp#, or pn#0 centered on x, y0, rotated  * #iven num)er o de#rees, rescaled to 5)y5.  * \param x te center x5coordinate o te ima#e  * \param y te center y5coordinate o te ima#e  * \param s te name o te ima#e/picture, e.#., ")all.#i"  * \param te idt o te ima#e  * \param te ei#t o te ima#e  * \param de#rees is te num)er o de#rees to rotate counterclocise  * \tros ;lle#al3r#umentException i te ima#e is corrupt  */

  pu)lic static void picturedou)le x, dou)le y, -trin# s, dou)le , dou)le, dou)le de#rees0 +  ;ma#e ima#e A #et;ma#es0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  dou)le s A actor0(  dou)le s A actor70(  i s S 6 s S 60 tro ne ;lle#al3r#umentException"ima#e " s " is corrupt"0(  i s SA & NN s SA &0 pixelx, y0(

  oscreen.rotateat.to>adians5de#rees0, xs, ys0(  oscreen.dra;ma#eima#e, int0 at.roundxs 5 s/9.60,  int0 at.roundys 5 s/9.60,  int0 at.rounds0,  int0 at.rounds0, null0(  oscreen.rotateat.to>adiansde#rees0, xs, ys0(

  dra0(  1

  /*************************************************************************  * =rain# text.  *************************************************************************/

  /**

  * Write te #iven text strin# in te current ont, centered on x, y0.  * \param x te center x5coordinate o te text  * \param y te center y5coordinate o te text  * \param s te text  */  pu)lic static void textdou)le x, dou)le y, -trin# s0 +  oscreen.setVontont0(  Vontetrics metrics A oscreen.#etVontetrics0(  dou)le xs A scalex0(  dou)le ys A scale7y0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 120/180

  int s A metrics.strin#Widts0(  int s A metrics.#et=escent0(  oscreen.dra-trin#s, loat0 xs 5 s/9.60, loat0 ys s00(  dra0(  1

  /**  * Write te #iven text strin# in te current ont, centered on x, y0 and  * rotated )y te speciied num)er o de#rees

* \param x te center x5coordinate o te text  * \param y te center y5coordinate o te text  * \param s te text  * \param de#rees is te num)er o de#rees to rotate counterclocise  */  pu)lic static void textdou)le x, dou)le y, -trin# s, dou)le de#rees0 +  dou)le xs A scalex0(  dou)le ys A scale7y0(  oscreen.rotateat.to>adians5de#rees0, xs, ys0(  textx, y, s0(  oscreen.rotateat.to>adiansde#rees0, xs, ys0(

  1

  /**  * Write te #iven text strin# in te current ont, let5ali#ned at x,y0.  * \param x te x5coordinate o te text  * \param y te y5coordinate o te text  * \param s te text  */  pu)lic static void textLetdou)le x, dou)le y, -trin# s0 +  oscreen.setVontont0(  Vontetrics metrics A oscreen.#etVontetrics0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  int s A metrics.#et=escent0(  oscreen.dra-trin#s, loat0 xs0, loat0 ys s00(  dra0(  1

  /**  * Write te #iven text strin# in te current ont, ri#t5ali#ned at x,y0.  * \param x te x5coordinate o te text  * \param y te y5coordinate o te text  * \param s te text  */

  pu)lic static void text>i#tdou)le x, dou)le y, -trin# s0 +  oscreen.setVontont0(  Vontetrics metrics A oscreen.#etVontetrics0(  dou)le xs A scalex0(  dou)le ys A scale7y0(  int s A metrics.strin#Widts0(  int s A metrics.#et=escent0(  oscreen.dra-trin#s, loat0 xs 5 s0, loat0 ys s00(  dra0(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 121/180

  /**  * =isplay on screen, pause or t milliseconds, and turn on  * SemManimation modeS/emM: su)seFuent calls to  * drain# metods suc as SttMline0S/ttM, SttMcircle0S/ttM, andSttMsFuare0S/ttM  * ill not )e displayed on screen until te next call to SttMso0S/ttM.  * %is is useul or producin# animations clear te screen, dra a )unco sapes,  * display on screen or a ixed amount o time, and repeat0. ;t alsospeeds up  * drain# a u#e num)er o sapes call SttMso60S/ttM to deer drain#  * on screen, dra te sapes, and call SttMso60S/ttM to display temall  * on screen at once0.  * \param t num)er o milliseconds  */  pu)lic static void soint t0 +

  deer A alse(  dra0(  try + %read.sleept0( 1  catc ;nterruptedException e0 + -ystem.out.println"Error sleepin#"0(1  deer A true(  1

  /**  * =isplay on5screen and turn o animation mode:  * su)seFuent calls to  * drain# metods suc as SttMline0S/ttM, SttMcircle0S/ttM, andSttMsFuare0S/ttM  * ill )e displayed on screen en called. %is is te deault.  */  pu)lic static void so0 +  deer A alse(  dra0(  1

  // dra onscreen i deer is alse  private static void dra0 +  i deer0 return(  onscreen.dra;ma#eoscreen;ma#e, 6, 6, null0(  rame.repaint0(  1

  /*************************************************************************  * -ave drain# to a ile.  *************************************************************************/

  /**  * -ave onscreen ima#e to ile 5 suix must )e pn#, jp#, or #i.  * \param ilename te name o te ile it one o te reFuired suixes  */  pu)lic static void save-trin# ilename0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 122/180

  Vile ile A ne Vileilename0(  -trin# suix A ilename.su)strin#ilename.last;ndex!.!0 &0(

  // pn# iles  i suix.toLoerCase0.eFuals"pn#"00 +  try + ;ma#e;.riteonscreen;ma#e, suix, ile0( 1  catc ;Exception e0 + e.print-tac%race0( 1  1

  // need to can#e rom 3>JB to >JB or jpe#  // reerence: ttp://arcives.java.sun.com/c#i5)in/a439Aind6?6?NLAjava9d5interestN=A6NPA9'9'  else i suix.toLoerCase0.eFuals"jp#"00 +  Writa)le>aster raster A onscreen;ma#e.#et>aster0(  Writa)le>aster ne>aster(  ne>aster A raster.createWrita)leCild6, 6, idt, ei#t, 6, 6,ne int +6, &, 910(  =irectColorodel cm A =irectColorodel0onscreen;ma#e.#etColorodel0(  =irectColorodel neC A ne =irectColorodelcm.#etPixel-iQe0,

  cm.#et>edas0,  cm.#etJreenas0,  cm.#etBlueas00(  Buered;ma#e r#)Buer A ne Buered;ma#eneC, ne>aster,alse, null0(  try + ;ma#e;.riter#)Buer, suix, ile0( 1  catc ;Exception e0 + e.print-tac%race0( 1  1

  else +  -ystem.out.println";nvalid ima#e ile type: " suix0(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void actionPerormed3ctionEvent e0 +  Vile=ialo# cooser A ne Vile=ialo#-td=ra.rame, "2se a .pn# or .jp#extension", Vile=ialo#.-3]E0(  cooser.set]isi)letrue0(  -trin# ilename A cooser.#etVile0(  i ilename OA null0 +  -td=ra.savecooser.#et=irectory0 Vile.separator cooser.#etVile00(  1

  1

  /*************************************************************************  * ouse interactions.  *************************************************************************/

  /**  * ;s te mouse )ein# pressed4  * \return true or alse

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 123/180

  */  pu)lic static )oolean mousePressed0 +  syncroniQed mouseLoc0 +  return mousePressed(  1  1

  /**  * Wat is te x5coordinate o te mouse4  * \return te value o te x5coordinate o te mouse  */  pu)lic static dou)le mouse0 +  syncroniQed mouseLoc0 +  return mouse(  1  1

  /**  * Wat is te y5coordinate o te mouse4  * \return te value o te y5coordinate o te mouse

  */  pu)lic static dou)le mouse70 +  syncroniQed mouseLoc0 +  return mouse7(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mouseClicedouseEvent e0 + 1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mouseEnteredouseEvent e0 + 1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mouseExitedouseEvent e0 + 1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mousePressedouseEvent e0 +

  syncroniQed mouseLoc0 +  mouse A -td=ra.usere.#et00(  mouse7 A -td=ra.user7e.#et700(  mousePressed A true(  1  1

  /**  * %is metod cannot )e called directly.  */

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 124/180

  pu)lic void mouse>eleasedouseEvent e0 +  syncroniQed mouseLoc0 +  mousePressed A alse(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mouse=ra##edouseEvent e0 +  syncroniQed mouseLoc0 +  mouse A -td=ra.usere.#et00(  mouse7 A -td=ra.user7e.#et700(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void mouseovedouseEvent e0 +

  syncroniQed mouseLoc0 +  mouse A -td=ra.usere.#et00(  mouse7 A -td=ra.user7e.#et700(  1  1

  /*************************************************************************  * <ey)oard interactions.  *************************************************************************/

  /**  * Has te user typed a ey4  * \return true i te user as typed a ey, alse oterise  */  pu)lic static )oolean asGext<ey%yped0 +  syncroniQed eyLoc0 +  return Oeys%yped.isEmpty0(  1  1

  /**  * Wat is te next ey tat as typed )y te user4 %is metod returns  * a 2nicode caracter correspondin# to te ey typed suc as !a! or!3!0.  * ;t cannot identiy action eys suc as V&  * and arro eys0 or modiier eys suc as control0.

  * \return te next 2nicode ey typed  */  pu)lic static car next<ey%yped0 +  syncroniQed eyLoc0 +  return eys%yped.removeLast0(  1  1

  /**

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 125/180

  * ;s te eycode currently )ein# pressed4 %is metod taes as anar#ument  * te eycode correspondin# to a pysical ey0. ;t can andle actioneys  * suc as V& and arro eys0 and modiier eys suc as sit andcontrol0.  * -ee Sa re A"ttp://donload.oracle.com/javase//docs/api/java/at/event/<eyEvent.tml"M<eyEvent.javaS/aM  * or a description o ey codes.  * \return true i eycode is currently )ein# pressed, alse oterise  */  pu)lic static )oolean is<eyPressedint eycode0 +  syncroniQed eyLoc0 +  return eys=on.containseycode0(  1  1

  /**

  * %is metod cannot )e called directly.  */  pu)lic void ey%yped<eyEvent e0 +  syncroniQed eyLoc0 +  eys%yped.addVirste.#et<eyCar00(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void eyPressed<eyEvent e0 +  syncroniQed eyLoc0 +  eys=on.adde.#et<eyCode00(  1  1

  /**  * %is metod cannot )e called directly.  */  pu)lic void ey>eleased<eyEvent e0 +  syncroniQed eyLoc0 +  eys=on.removee.#et<eyCode00(  1  1

  /**  * %est client.  */  pu)lic static void main-trin# ar#s0 +  -td=ra.sFuare.9, .K, .&0(  -td=ra.illed-Fuare.K, .K, .90(  -td=ra.circle.K, .9, .90(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 126/180

  -td=ra.setPenColor-td=ra.B<[>E=0(  -td=ra.setPen>adius.690(  -td=ra.arc.K, .9, .&, 966, ?@0(

  // dra a )lue diamond  -td=ra.setPen>adius0(  -td=ra.setPenColor-td=ra.B<[BL2E0(  dou)le x A + .&, .9, .8, .9 1(  dou)le y A + .9, .8, .9, .& 1(  -td=ra.illedPoly#onx, y0(

  // text  -td=ra.setPenColor-td=ra.BL3C<0(  -td=ra.text6.9, 6.@, ")lac text"0(  -td=ra.setPenColor-td=ra.WH;%E0(  -td=ra.text6.K, 6.K, "ite text"0(  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" )!e 5ct 23 0%"10"2% ($) 201.

t#Au#io.java

Below is the syntax highlighted version of 9tdAudio.java from § 9tandard )i&raries. Here is the

+avado(.

/************************************************************************* * Compilation: javac -td3udio.java * Execution: java -td3udio ** -imple li)rary or readin#, ritin#, and manipulatin# .av iles.

 * * Limitations * 55555555555 * 5 =oes not seem to or properly en readin# .av iles rom a .jarile. * 5 3ssumes te audio is monaural, it samplin# rate o ??,&66. *

  *************************************************************************/

import java.applet.*(import java.io.*(import java.net.*(import javax.sound.sampled.*(

/** * SiM-tandard audioS/iM. %is class provides a )asic capa)ility or * creatin#, readin#, and savin# audio.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 127/180

 * SpM * %e audio ormat uses a samplin# rate o ??,&66 C= Fuality audio0, &5)it, monaural. * * SpM * Vor additional documentation, see SareA"ttp://introcs.cs.princeton.edu/&@inout"M-ection &.@S/aM o * SiM;ntroduction to Pro#rammin# in Uava: 3n ;nterdisciplinary 3pproacS/iM)y >o)ert -ed#eic and <evin Wayne. * * \autor >o)ert -ed#eic * \autor <evin Wayne */pu)lic inal class -td3udio +

  /**  * %e sample rate 5 ??,&66 HQ or C= Fuality audio.  */  pu)lic static inal int -3PLE[>3%E A ??&66(

  private static inal int B7%E-[PE>[-3PLE A 9( // &5)itaudio  private static inal int B;%-[PE>[-3PLE A &( // &5)itaudio  private static inal dou)le 3[&[B;% A -ort.3[]3L2E( // 89,''  private static inal int -3PLE[B2VVE>[-;^E A ?6D(

  private static -ource=ataLine line( // to play te sound  private static )yte )uer( // our internal )uer  private static int )uer-iQe A 6( // num)er o samples currently ininternal )uer

  // do not instantiate  private -td3udio0 + 1

 // static initialiQer

  static + init0( 1

  // open up an audio stream  private static void init0 +  try +  // ??,&66 samples per second, &5)it audio, mono, si#ned PC,little Endian  3udioVormat ormat A ne 3udioVormatloat0 -3PLE[>3%E,B;%-[PE>[-3PLE, &, true, alse0(

  =ataLine.;no ino A ne =ataLine.;no-ource=ataLine.class,ormat0(

  line A -ource=ataLine0 3udio-ystem.#etLineino0(  line.openormat, -3PLE[B2VVE>[-;^E * B7%E-[PE>[-3PLE0( 

// te internal )uer is a raction o te actual )uer siQe,tis coice is ar)itrary  // it #ets divided )ecause e can!t expect te )uered data toline up exactly it en

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 128/180

  // te sound card decides to pus out its samples.  )uer A ne )yte-3PLE[B2VVE>[-;^E * B7%E-[PE>[-3PLE/8(  1 catc Exception e0 +  -ystem.out.printlne.#etessa#e00(  -ystem.exit&0(  1

  // no sound #ets made )eore tis call  line.start0(  1

  /**  * Close standard audio.  */  pu)lic static void close0 +  line.drain0(  line.stop0(  1 

/**  * Write one sample )eteen 5&.6 and &.60 to standard audio. ; tesample  * is outside te ran#e, it ill )e clipped.  */  pu)lic static void playdou)le in0 +

  // clip i outside 5&, &  i in S 5&.60 in A 5&.6(  i in M &.60 in A &.6(

  // convert to )ytes  sort s A sort0 3[&[B;% * in0(  )uer)uer-iQe A )yte0 s(  )uer)uer-iQe A )yte0 s MM K0( // little Endian

  // send to sound card i )uer is ulli )uer-iQe MA )uer.len#t0 +

  line.rite)uer, 6, )uer.len#t0(  )uer-iQe A 6(  1  1

  /**  * Write an array o samples )eteen 5&.6 and &.60 to standard audio. ;a sample  * is outside te ran#e, it ill )e clipped.

  */  pu)lic static void playdou)le input0 +  or int i A 6( i S input.len#t( i0 +  playinputi0(  1  1

  /**  * >ead audio samples rom a ile in .av or .au ormat0 and return temas a dou)le array

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 129/180

  * it values )eteen 5&.6 and &.6.  */  pu)lic static dou)le read-trin# ilename0 +  )yte data A readByteilename0(  int G A data.len#t(  dou)le d A ne dou)leG/9(  or int i A 6( i S G/9( i0 +  di A sort0 data9*i& N 6xVV0 SS K0 data9*i N6xVV000 / dou)le0 3[&[B;%0(  1  return d(  1

  /**  * Play a sound ile in .av, .mid, or .au ormat0 in a )ac#roundtread.  */

  pu)lic static void play-trin# ilename0 +  2>L url A null(  try +  Vile ile A ne Vileilename0(  i ile.can>ead00 url A ile.to2>;0.to2>L0(  1  catc alormed2>LException e0 + e.print-tac%race0( 1  // 2>L url A -td3udio.class.#et>esourceilename0(  i url AA null0 tro ne >untimeException"audio " ilename "not ound"0(  3udioClip clip A 3pplet.ne3udioClipurl0(  clip.play0(  1

  /**  * Loop a sound ile in .av, .mid, or .au ormat0 in a )ac#roundtread.  */  pu)lic static void loop-trin# ilename0 +  2>L url A null(  try +  Vile ile A ne Vileilename0(  i ile.can>ead00 url A ile.to2>;0.to2>L0(  1  catc alormed2>LException e0 + e.print-tac%race0( 1  // 2>L url A -td3udio.class.#et>esourceilename0(  i url AA null0 tro ne >untimeException"audio " ilename "

not ound"0(  3udioClip clip A 3pplet.ne3udioClipurl0(  clip.loop0(  1

  // return data as a )yte array  private static )yte readByte-trin# ilename0 +  )yte data A null(  3udio;nput-tream ais A null(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 130/180

  try +

  // try to read rom ile  Vile ile A ne Vileilename0(  i ile.exists00 +  ais A 3udio-ystem.#et3udio;nput-treamile0(  data A ne )yteais.availa)le0(  ais.readdata0(  1

  // try to read rom 2>L  else +  2>L url A -td3udio.class.#et>esourceilename0(  ais A 3udio-ystem.#et3udio;nput-treamurl0(  data A ne )yteais.availa)le0(  ais.readdata0(  1  1  catc Exception e0 +  -ystem.out.printlne.#etessa#e00(

  tro ne >untimeException"Could not read " ilename0(  1

  return data(  1

  /**  * -ave te dou)le array as a sound ile usin# .av or .au ormat0.  */  pu)lic static void save-trin# ilename, dou)le input0 +

  // assumes ??,&66 samples per second  // use &5)it audio, mono, si#ned PC, little Endian  3udioVormat ormat A ne 3udioVormat-3PLE[>3%E, &, &, true, alse0(  )yte data A ne )yte9 * input.len#t(  or int i A 6( i S input.len#t( i0 +  int temp A sort0 inputi * 3[&[B;%0(  data9*i 6 A )yte0 temp(  data9*i & A )yte0 temp MM K0(  1

  // no save te ile  try +  Byte3rray;nput-tream )ais A ne Byte3rray;nput-treamdata0(  3udio;nput-tream ais A ne 3udio;nput-tream)ais, ormat,

input.len#t0(  i ilename.endsWit".av"0 ilename.endsWit".W3]"00 +  3udio-ystem.riteais, 3udioVileVormat.%ype.W3]E, neVileilename00(  1  else i ilename.endsWit".au"0 ilename.endsWit".32"00 +  3udio-ystem.riteais, 3udioVileVormat.%ype.32, neVileilename00(  1  else +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 131/180

  tro ne >untimeException"Vile ormat not supported: " ilename0(  1  1  catc Exception e0 +  -ystem.out.printlne0(  -ystem.exit&0(  1  1

  /***********************************************************************  * sample test client  ***********************************************************************/

  // create a note sine ave0 o te #iven reFuency HQ0, or te #iven  // duration seconds0 scaled to te #iven volume amplitude0  private static dou)le notedou)le Q, dou)le duration, dou)le amplitude0

+  int G A int0 -td3udio.-3PLE[>3%E * duration0(  dou)le a A ne dou)leG&(  or int i A 6( i SA G( i0  ai A amplitude * at.sin9 * at.P; * i * Q /-td3udio.-3PLE[>3%E0(  return a(  1

  /**  * %est client 5 play an 3 major scale to standard audio.  */  pu)lic static void main-trin# ar#s0 + 

// ??6 HQ or & sec  dou)le reF A ??6.6(  or int i A 6( i SA -td3udio.-3PLE[>3%E( i0 +  -td3udio.play6.@ * at.sin9*at.P; * reF * i /-td3udio.-3PLE[>3%E00(  1 

// scale increments  int steps A + 6, 9, ?, @, ', D, &&, &9 1(  or int i A 6( i S steps.len#t( i0 +  dou)le Q A ??6.6 * at.po9, stepsi / &9.60(  -td3udio.playnoteQ, &.6, 6.@00(  1

  // need to call tis in non5interactive stu so te pro#ram doesn!tterminate  // until all te sound leaves te speaer.  -td3udio.close0(

// need to terminate a Uava pro#ram it sound  -ystem.exit60(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 132/180

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )!e Sep 1% 14"2"0 ($) 201.

A##Ints.java

Below is the syntax highlighted version of AddInts.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac 3dd;nts.java * Execution: java 3dd;nts * =ependencies: -td;n.java ** %is pro#ram taes a command line ar#ument G, reads in G inte#ers, * and prints out teir sum. * * Gote: you must av te ile -td;n.java in your orin# directory. * * $ java 3dd;nts G *  *************************************************************************/

pu)lic class 3dd;nts+

pu)lic static void main-trin# ar#s0  +

int G A ;nte#er.parse;ntar#s60(  int sum A 6(  or int i A 6( i S G( i0  sum A sum -td;n.read;nt0(  -ystem.out.println"-um is " sum0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

 T,enty"uestions.java

Below is the syntax highlighted version of Twenty'uestions.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac %entyIuestions.java

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 133/180

 * Execution: java %entyIuestions * =ependencies -td;n.java * * $ java %entyIuestions* ;!m tinin# o a num)er )eteen & and &,666,666* Wat!s your #uess4 @66666* %oo i#* Wat!s your #uess4 9@6666* %oo lo* Wat!s your #uess4 8'@666* %oo i#* Wat!s your #uess4 8&9@66* %oo i#* Wat!s your #uess4 866@66* %oo lo* ...*  *************************************************************************/

pu)lic class %entyIuestions +

  pu)lic static void main-trin# ar#s0 +

  // Jenerate a num)er and anser Fuestions  // ile te user tries to #uess te value.  int G A & int0 at.random0 * &6666660(

  -tdut.print";!m tinin# o a num)er "0(  -tdut.println")eteen & and &,666,666"0(  int m A 6(

ile m OA G0 +

  // -olicit one #uess and provide one anser  -tdut.print"Wat!s your #uess4 "0(  m A -td;n.read;nt0(  i m AA G0 -tdut.println"7ou inO"0(  i m S G0 -tdut.println"%oo lo "0(  i m M G0 -tdut.println"%oo i#"0(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Average.java

Below is the syntax highlighted version of Average.java from §1.; In#ut and %ut#ut.

/*************************************************************************

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 134/180

 * Compilation: javac 3vera#e.java * Execution: java 3vera#e S data.txt * =ependencies: -td;n.java -tdut.java ** >eads in a seFuence o real num)ers, and computes teir avera#e. * * $ java 3vera#e * &6.6 @.6 .6 * 8.6 '.6 89.6 * SCtrl5dM * 3vera#e is &6.@

 * Gote SCtrl5dM si#niies te end o ile on 2nix. * n indos use SCtrl5QM. *  *************************************************************************/

pu)lic class 3vera#e +pu)lic static void main-trin# ar#s0 +

int count A 6( // num)er input values

  dou)le sum A 6.6( // sum o input values

  // read data and compute statistics  ile O-td;n.isEmpty00 +  dou)le value A -td;n.read=ou)le0(  sum A value(  count(  1

  // compute te avera#e  dou)le avera#e A sum / count(

  // print results  -tdut.println"3vera#e is " avera#e0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

 Triangle.java

Below is the syntax highlighted version of Triangle.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac %rian#le.java * Execution: java %rian#le * =ependencies: -td=ra.java * * Plot a trian#le. *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 135/180

  *************************************************************************/

pu)lic class %rian#le +  pu)lic static void main-trin# ar#s0 +  dou)le t A at.sFrt8.60 / 9.6(  -td=ra.line6.6, 6.6, &.6, 6.60(  -td=ra.line&.6, 6.6, 6.@, t0(  -td=ra.line6.@, t, 6.6, 6.60(  -td=ra.point6.@, t/8.60(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

)lotilter.java

Below is the syntax highlighted version of lot,ilter.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac PlotVilter.java * Execution: java PlotVilter S input.txt * =ependencies: -td=ra.java -td;n.java ** $ java PlotVilter S 2-3.txt * * =atailes: ttp://.cs.princeton.edu/;ntroPro#rammin#/&@inout/2-3.txt

 *  *************************************************************************/

pu)lic class PlotVilter +

pu)lic static void main-trin# ar#s0 +

  // read in )oundin# )ox and rescale  dou)le x6 A -td;n.read=ou)le0(  dou)le y6 A -td;n.read=ou)le0(  dou)le x& A -td;n.read=ou)le0(  dou)le y& A -td;n.read=ou)le0(  -td=ra.setscalex6, x&0(  -td=ra.set7scaley6, y&0(

  // turn on animation mode to deer displayin# all o te points  // -td=ra.so60(

  // plot points, one at a time  ile O-td;n.isEmpty00 +  dou)le x A -td;n.read=ou)le0(  dou)le y A -td;n.read=ou)le0(  -td=ra.pointx, y0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 136/180

  1

  // display all o te points no  // -td=ra.so60(

  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

un$tionraph.java

Below is the syntax highlighted version of ,un(tion>ra#h.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac VunctionJrap.java* Execution: java VunctionJrap * =ependencies: -td=ra.java * * Plots te unction y A sin?x0 sin96x0 )eteen x A 6 and x A pi * )y drain# G line se#ments. *  *************************************************************************/

pu)lic class VunctionJrap +  pu)lic static void main-trin# ar#s0 +

  // num)er o line se#ments to plot  int G A ;nte#er.parse;ntar#s60(

  // te unction y A sin?x0 sin96x0, sampled at G points  // )eteen x A 6 and x A pi  dou)le x A ne dou)leG&(  dou)le y A ne dou)leG&(  or int i A 6( i SA G( i0 +  xi A at.P; * i / G(  yi A at.sin?*xi0 at.sin96*xi0(  1

  // rescale te coordinate system  -td=ra.setscale6, at.P;0(  -td=ra.set7scale59.6, 9.60(

  // plot te approximation to te unction  or int i A 6( i S G( i0 +  -td=ra.linexi, yi, xi&, yi&0(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 137/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Boun$ingBall.java

Below is the syntax highlighted version of Boun(ingBall.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Bouncin#Ball.java * Execution: java Bouncin#Ball * =ependencies: -td=ra.java * * ;mplementation o a 95d )ouncin# )all in te )ox rom 5&, 5&0 to &, &0. * * $ java Bouncin#Ball *

  *************************************************************************/

pu)lic class Bouncin#Ball +pu)lic static void main-trin# ar#s0 +

  // set te scale o te coordinate system  -td=ra.setscale5&.6, &.60(  -td=ra.set7scale5&.6, &.60(

  // initial values  dou)le rx A 6.?K6, ry A 6.K6( // position  dou)le vx A 6.6&@, vy A 6.698( // velocity  dou)le radius A 6.6@( // radius

  // main animation loop  ile true0 +

// )ounce o all accordin# to la o elastic collision  i at.a)srx vx0 M &.6 5 radius0 vx A 5vx(  i at.a)sry vy0 M &.6 5 radius0 vy A 5vy(

  // update position  rx A rx vx(

ry A ry vy(

// clear te )ac#round  -td=ra.setPenColor-td=ra.J>370(

  -td=ra.illed-Fuare6, 6, &.60(

  // dra )all on te screen  -td=ra.setPenColor-td=ra.BL3C<0(

-td=ra.illedCirclerx, ry, radius0(

// display and pause or 96 ms  -td=ra.so960(

11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 138/180

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Delu'eBoun$ingBall.java

Below is the syntax highlighted version of $eluxeBoun(ingBall.java from §1.; In#ut and

%ut#ut.

/************************************************************************* * Compilation: javac =eluxeBouncin#Ball.java * Execution: java =eluxeBouncin#Ball * =ependencies: -td=ra.java -td3udio.java

 * ttp://.cs.princeton.edu/introcs/&@inout/laser.av * ttp://.cs.princeton.edu/introcs/&@inout/pop.av * ttp://.cs.princeton.edu/introcs/&@inout/eart.#i * * ;mplementation o a 95d )ouncin# )all in te )ox rom 5&, 5&0 to &, &0. * * $ java =eluxeBouncin#Ball *  *************************************************************************/

pu)lic class =eluxeBouncin#Ball +pu)lic static void main-trin# ar#s0 +

  dou)le rx A .?K6, ry A .K6( // position  dou)le vx A .6&@, vy A .698( // velocity  dou)le radius A .68( // a ac since "eart.#i" is inpixels

  // set te scale o te coordinate system  -td=ra.setscale5&.6, &.60(  -td=ra.set7scale5&.6, &.60(

  // main animation loop  ile true0 +

i at.a)srx vx0 radius M &.60 + vx A 5vx(-td3udio.play"laser.av"0( 1  i at.a)sry vy0 radius M &.60 + vy A 5vy(

-td3udio.play"pop.av"0( 1  rx A rx vx(

ry A ry vy(-td=ra.illed-Fuare6.6, 6.6, &.60(

  -td=ra.picturerx, ry, "eart.#i"0(  -td=ra.so960(

11

1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 139/180

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )h! Sep 23 12"4"11 ($) 2011.

6ouseollo,er.java

Below is the syntax highlighted version of ?ouse,ollower.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac ouseVolloer.java * Execution: java ouseVolloer * =ependencies: -td=ra.java * * =ra a )lue illed circle erever te mouse is, in cyan i te * mouse is pressed. * * * $ java ouseVolloer * * Credits: Ue %raer5Bernstein *  *************************************************************************/

pu)lic class ouseVolloer +  pu)lic static void main-trin# ar#s0 +  ile true0 +

  // mouse clic  i -td=ra.mousePressed00 -td=ra.setPenColor-td=ra.C73G0(  else -td=ra.setPenColor-td=ra.BL2E0(

  // mouse location  -td=ra.clear0(  dou)le x A -td=ra.mouse0(  dou)le y A -td=ra.mouse70(  -td=ra.illedCirclex, y, .6@0(  -td=ra.so&60(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

neimpleAttra$tor.java

Below is the syntax highlighted version of %ne9im#leAttra(tor.java from §1.; In#ut and %ut#ut. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 140/180

/************************************************************************* * Compilation: javac ne-imple3ttractor.java * Execution: java ne-imple3ttractor

 * =ependencies: -td=ra.java * * 3 particle is attracted to te current location o te mouse. * ;ncorporates dra#. * ** $ java ne-imple3ttractor * * * Credits: Ue %raer5Bernstein *  *************************************************************************/

pu)lic class ne-imple3ttractor +  pu)lic static void main-trin# ar#s0 +  dou)le rx A 6.6, ry A 6.6( // position  dou)le vx A 6.6, vy A 6.6( // velocity  dou)le mass A &.6( // mass  dou)le dt A 6.@( // time Fuantum  dou)le dra# A 6.&( // mess around it tis a )it  dou)le attraction-tren#t A 6.6&( 

// do te animation  ile true0 +

  // compute te attractive orce to te mouse, accountin# or dra#  dou)le dx A -td=ra.mouse0 5 rx(  dou)le dy A -td=ra.mouse70 5 ry(  dou)le x A dx * attraction-tren#t0 5 dra# * vx0(  dou)le y A dy * attraction-tren#t0 5 dra# * vy0( 

// Euler step: update velocity, ten position  vx A x * dt / mass(  vy A y * dt / mass(  rx A vx * dt(  ry A vy * dt( 

// dra particle

  -td=ra.clear0(  -td=ra.setPenColor-td=ra.BL2E0(  -td=ra.illedCirclerx, ry, .690(  -td=ra.so&60(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 141/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

impleAttra$tors.java

Below is the syntax highlighted version of 9im#leAttra(tors.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac -imple3ttractors.java * Execution: java -imple3ttractors G * =ependencies: -td=ra.java * * G particles are attracted to te mouse( randomly rearran#e en * user clics. *

 * $ java -imple3ttractors 96 * * Credits: Ue %raer5Bernstein **************************************************************************/

pu)lic class -imple3ttractors +  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(  dou)le rx A ne dou)leG(  dou)le ry A ne dou)leG(  dou)le vx A ne dou)leG(  dou)le vy A ne dou)leG(  dou)le dt A 6.@(  dou)le mass A &.6(  dou)le dra# A 6.6@( // try can#in# tis to 6.& or 6.6& or even6...  dou)le attraction-tren#t A 6.6&( 

// initialiQe te drain# area  -td=ra.setPenColor-td=ra.BL2E0(

  // do te animation  ile true0 +  // i te mouse is pressed add some random velocity to all teparticles  i -td=ra.mousePressed00 +

  or int i A 6( i S G( i0 +  vxi A .9 * at.random0 5 .&(  vyi A .9 * at.random0 5 .&(  1  1 

// clear all te orces  dou)le x A ne dou)leG(  dou)le y A ne dou)leG( 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 142/180

  // add attraction orces or attraction to te mouse  or int i A 6( i S G( i0 +  dou)le dx A -td=ra.mouse0 5 rxi(  dou)le dy A -td=ra.mouse70 5 ryi(  xi A attraction-tren#t * dx(  yi A attraction-tren#t * dy(  1 

// add dra# orces to all particles  // dra# is proportional to velocity in te opposite direction  or int i A 6( i S G( i0 +  xi A 5dra# * vxi(  yi A 5dra# * vyi(  1 

// update positions  // euler step  or int i A 6( i S G( i0 +  vxi A xi * dt / mass(  vyi A yi * dt / mass(

  rxi A vxi * dt(  ryi A vyi * dt(  1 

-td=ra.clear0( 

// dra a illed circle or eac particle  or int i A 6( i S G( i0 +  -td=ra.illedCirclerxi, ryi, .6&0(  1 

-td=ra.so&60(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

prings.java

Below is the syntax highlighted version of 9#rings.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac -prin#s.java * Execution: java -prin#s G * =ependencies: -td=ra.java * * -imulates a system o sprin#s.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 143/180

 * * $ java -prin#s &@ * * Credits: Ue %raer5Bernstein *  *************************************************************************/

pu)lic class -prin#s +  pu)lic static void main-trin# ar#s0 +  // mess around it tis, try ', K, D, &6, &&, &9, &@  // pro)a)ly ave to turn don te sprin# orce to eep it sta)le atertat...  int G A ;nte#er.parse;ntar#s60(

  dou)le rx A ne dou)leG(  dou)le ry A ne dou)leG(  dou)le vy A ne dou)leG(  dou)le vx A ne dou)leG(  dou)le particleass A &.6(

  dou)le dra# A 6.&(  dou)le sprin#-tren#t A 6.&(  dou)le sprin#Len#t A 86(  dou)le #ravity A &.6(  dou)le time-tep A 6.@( 

// set up te drain# area  -td=ra.setscale6, &660(  -td=ra.set7scale6, &660(  -td=ra.setPenColor-td=ra.BL2E0(  -td=ra.setPen>adius6.669@0( 

// initialiQe te particle positions randomly  or int i A 6( i S G( i0 +  rxi A &66 * at.random0(  ryi A &66 * at.random0(  1 

// do te animation  ile true0 +

  // clear all te orces  dou)le x A ne dou)leG(  dou)le y A ne dou)leG( 

// sprin# orces act )eteen every pairin# o particles

  // sprin# orce is proportional to te dierence )eteen te restlen#t o te sprin#  // and te distance )eteen te 9 particles it!s actin# on  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +

  i i AA j0 continue(

  // calculate distance )eteen particles i and j  dou)le dx A rxj 5 rxi(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 144/180

  dou)le dy A ryj 5 ryi(  dou)le len#t A at.sFrtdx*dx dy*dy0( 

// i#ure out te orce  dou)le orce A sprin#-tren#t * len#t 5 sprin#Len#t0(  dou)le sprin#Vorce A orce * dx / len#t(  dou)le sprin#Vorce7 A orce * dy / len#t( 

// update te orce  xi A sprin#Vorce(  yi A sprin#Vorce7(  1  1 

// add dra# orce  // dra# is proportional to velocity )ut in te opposite direction  or int i A 6( i S G( i0 +  xi A 5dra# * vxi(  yi A 5dra# * vyi(  1

 // add #ravity orces

  // just add some orce pointin# don to all o tem  or int i A 6( i S G( i0 +  yi A 5#ravity(  1 

// ix particle & at te mouse position  rx6 A -td=ra.mouse0(  ry6 A -td=ra.mouse70(  vx6 A 6.6(  vy6 A 6.6(  x6 A 6.6(  y6 A 6.6( 

// update positions usin# approximation  or int i A 6( i S G( i0 +  vxi A xi * time-tep/particleass(  vyi A yi * time-tep/particleass(  rxi A vxi * time-tep(  ryi A vyi * time-tep(  1 

// clear  -td=ra.clear0( 

// dra everytin#  or int i A 6( i S G( i0 +  // dra a circle or eac node  -td=ra.illedCirclerxi, ryi, &.60( 

// dra te connections )eteen every 9 nodes  or int j A 6( j S i( j0 +  -td=ra.linerxi, ryi, rxj, ryj0(  1  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 145/180

 // so and ait

  -td=ra.so&60(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

)layThatTune.java

Below is the syntax highlighted version of layThatTune.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Play%at%une.java * Execution: java Play%at%une S input.txt * =ependencies: -td3udio.java -td3udio.java * * %is is a data5driven pro#ram tat plays pure tones rom * te notes on te cromatic scale, speciied on standard input * )y teir distance rom concert 3. * * $ java Play%at%une S elise.txt * * * =ata iles * 5555555555

 * ttp://.cs.princeton.edu/introcs/9&unction/elise.txt * ttp://.cs.princeton.edu/introcs/9&unction/DDlut)allons.txt * ttp://.cs.princeton.edu/introcs/9&unction/ree)ird.txt * ttp://.cs.princeton.edu/introcs/9&unction/3scale.txt * ttp://.cs.princeton.edu/introcs/9&unction/Gational[3ntem.txt * ttp://.cs.princeton.edu/introcs/9&unction/looney.txt * ttp://.cs.princeton.edu/introcs/9&unction/-tairay%oHeaven.txt * ttp://.cs.princeton.edu/introcs/9&unction/entertainer.txt * ttp://.cs.princeton.edu/introcs/9&unction/old5nassau.txt * ttp://.cs.princeton.edu/introcs/9&unction/ara)esFue.txt * ttp://.cs.princeton.edu/introcs/9&unction/irstcut.txt* ttp://.cs.princeton.edu/introcs/9&unction/tomsdiner.txt *  *************************************************************************/

pu)lic class Play%at%une +

  pu)lic static void main-trin# ar#s0 +

  // repeat as lon# as tere are more inte#ers to read in  ile O-td;n.isEmpty00 +

  // read in te pitc, ere 6 A Concert 3 3?0

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 146/180

  int pitc A -td;n.read;nt0(

  // read in duration in seconds  dou)le duration A -td;n.read=ou)le0(

  // )uild sine ave it desired reFuency  dou)le Q A ??6 * at.po9, pitc / &9.60(  int G A int0 -td3udio.-3PLE[>3%E * duration0(  dou)le a A ne dou)leG&(  or int i A 6( i SA G( i0 +  ai A at.sin9 * at.P; * i * Q / -td3udio.-3PLE[>3%E0(  1

  // play it usin# standard audio  -td3udio.playa0(  1  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed 5ct 12 04"++"+3 ($) 2011.

6a'6in.java

Below is the syntax highlighted version of ?ax?in.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac axin.java

* Execution: java axin * input reFuired rom standard input  * use Ctrl5d - or =r. Uava0 or Ctrl5Q Windos0 or EV  * * =ependencies: -td;n.java -tdut.java * * >ead in inte#ers rom standard input and print out te maximum and * minimum values. * * $ java axin * 98 ?@ &' @ 89 * KD &6 @8 89 8? * & * Ctrl5d * maximum A KD, minimum A &6 *  *************************************************************************/

pu)lic class axin +  pu)lic static void main-trin# ar#s0 + 

// irst value read initialiQed min and max  int max A -td;n.read;nt0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 147/180

  int min A max( 

// read in te data, eep trac o min and max  ile O-td;n.isEmpty00 +  int value A -td;n.read;nt0(  i value M max0 max A value(  i value S min0 min A value(  1 

// output  -tdut.println"maximum A " max ", minimum A " min0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

tats.java

Below is the syntax highlighted version of 9tats.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac -tats.java * Execution: java -tats G * =ependencies: -td;n.java -tdut.java ** >eads in a command5line inte#er G, a seFuence o G real num)ers rom

 * standard input, and prints te mean and standard deviation. * * $ java -tats  * &6.6 @.6 .6 * 8.6 '.6 89.6 * SCtrl5dM * ean A &6.@ * -tandard deviation A ?.K99K9996'&?DD' * * Gote SCtrl5dM si#niies te end o ile on 2nix. * n indos use SCtrl5QM. *  *************************************************************************/

pu)lic class -tats +pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  dou)le a A ne dou)leG(

  // read data and compute statistics  or int i A 6( i S G( i0 +  ai A -td;n.read=ou)le0(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 148/180

  // compute mean  dou)le sum A 6.6(  or int i A 6( i S G( i0 +  sum A ai(  1  dou)le mean A sum / G(

  // compute standard deviation  dou)le sum9 A 6.6(  or int i A 6( i S G( i0 +  sum9 A ai 5 mean0 * ai 5 mean0(  1  dou)le stddev A at.sFrtsum90 / G 5 &0(

  // print results  -tdut.println"ean A " mean0(  -tdut.println"-tandard deviation A " stddev0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

%ongestRun.java

Below is the syntax highlighted version of )ongestun.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Lon#est>un.java* Execution: java Lon#est>un * input reFuired rom standard input  * use Ctrl5d - or =r. Uava0 or Ctrl5Q Windos0 or EV  * * =ependencies: -td;n.java -tdut.java * * >ead in a seFuence o inte#ers and prints out )ot te inte#er * tat appears in a lon#est consecutive run and len#t o te run. * * $ java Lon#est>un * & 9 9 & @ & & ' ' ' ' & & * Ctrl5d * Lon#est run: ? consecutive 's *  *************************************************************************/

pu)lic class Lon#est>un +  pu)lic static void main-trin# ar#s0 +

  // de#enerate case it no input inte#ers  i -td;n.isEmpty00 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 149/180

  -tdut.println"no lon#est consecutive run"0(  return(  1

  int prev A -td;n.read;nt0(  int count A &(  int )est A prev(  int )estCount A count(

  ile O-td;n.isEmpty00 +  // read in te next value  int current A -td;n.read;nt0(

  // update current run  i current AA prev0 count(  else +  prev A current(  count A &(  1

  // update campion values  i count M )estCount0 +  )estCount A count(  )est A current(  1  1 

// output  -tdut.println"Lon#est run: " )estCount " consecutive " )est "s"0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Dragon.java

Below is the syntax highlighted version of $ragon.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac =ra#on.java * Execution: eco V V java =ra#on java =ra#on java =ra#on ** Prints te instructions or drain# a dra#on curve o orders G. ** $ eco V V java =ra#on* VLV V>V *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 150/180

 * $ eco V V java =ra#on java =ra#on* VLVLV>V VLV>V>V * * $ eco V V java =ra#on java =ra#on java =ra#on * VLVLV>VLVLV>V>V VLVLV>V>VLV>V>V *  *************************************************************************/

pu)lic class =ra#on +pu)lic static void main-trin# ar#s0 +

-trin# dra#on A -td;n.read-trin#0(  -trin# no#ard A -td;n.read-trin#0(  -ystem.out.printdra#on "L" no#ard0(  -ystem.out.print" "0(  -ystem.out.printdra#on ">" no#ard0(  -ystem.out.println0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

+or#Gount.java

Below is the syntax highlighted version of Word5ount.java from §1.; In#ut and %ut#ut.

/*************************************************************************

 * Compilation: javac WordCount.java* Execution: java WordCount * input reFuired rom standard input  * use Ctrl5d - or =r. Uava0 or Ctrl5Q Windos0 or EV  * * =ependencies: -td;n.java -tdut.java * * >ead in a seFuence o strin#s rom standard input and print out * te num)er o strin#s read in. * * $ java WordCount * it as te )est o times * it as te orst o times * num)er o ords A &9 * Ctrl5d * * $ java WordCount S tale.txt* num)er o ords A &8D6?8 *  *************************************************************************/

pu)lic class WordCount +  pu)lic static void main-trin# ar#s0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 151/180

  int count A 6(ile O-td;n.isEmpty00 +

  -trin# ord A -td;n.read-trin#0(  count(  1 

// output  -tdut.println"num)er o ords A " count0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Glosest.java

Below is the syntax highlighted version of 5losest.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac Closest.java* Execution: java Closest x y Q * input reFuired rom standard input  * use Ctrl5d - or =r. Uava0 or Ctrl5Q Windos0 or EV  * * =ependencies: -td;n.java -tdut.java *

 * %aes tree command5line ar#uments x, y, Q( reads rom standard input a * seFuence o point coordinates xi, yi, Qi0, and prints te coordinates * o te point closest to x, y, Q0. * * $ java Closest &.6 @.6 9.6 * &.6 8.6 D.6 * @.6 8.6 9.@ * D.6 .6 9.6 * 9.6 .6 8.6 * @.6 .6 @.6 * SCtrl5dM * Closest point A 9.666666, .666666, 8.6666660*  *************************************************************************/

pu)lic class Closest +  pu)lic static void main-trin# ar#s0 +  dou)le x A =ou)le.parse=ou)lear#s60(  dou)le y A =ou)le.parse=ou)lear#s&0(  dou)le Q A =ou)le.parse=ou)lear#s90(

  dou)le )estx A =ou)le.GaG(  dou)le )esty A =ou)le.GaG(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 152/180

  dou)le )estQ A =ou)le.GaG(  dou)le )est=ist9 A =ou)le.P-;%;]E[;GV;G;%7(

  ile O-td;n.isEmpty00 +  dou)le xi A -td;n.read=ou)le0(  dou)le yi A -td;n.read=ou)le0(  dou)le Qi A -td;n.read=ou)le0(  dou)le dist9 A x 5 xi0 * x 5 xi0 y 5 yi0 * y 5 yi0 Q 5Qi0 * Q 5 Qi0(  i dist9 S )est=ist90 +  )estx A xi(  )esty A yi(  )estQ A Qi(  )est=ist9 A dist9(  1  1

  // output  -tdut.print"Closest point A $, $, $0Zn", )estx, )esty, )estQ0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Ghe$8erBoar#.java

Below is the syntax highlighted version of 5he(2erBoard.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac CecerBoard.java* Execution: java CecerBoard G * =ependencies: -td=ra.java * * Plots an G5)y5G cecer )oard. *  *************************************************************************/

pu)lic class CecerBoard +

pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  -td=ra.setscale6, G0(  -td=ra.set7scale6, G0(

  or int i A 6( i S G( i0 +  or int j A 6( j S G( j0 +  i i j0 $ 9 OA 60 -td=ra.setPenColor-td=ra.BL3C<0(  else -td=ra.setPenColor-td=ra.>E=0(  -td=ra.illed-Fuarei .@, j .@, .@0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 153/180

  1  1  -td=ra.so0(  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" on #eb 1+ 0%"13"% (S) 2011.

Rose.java

Below is the syntax highlighted version of ose.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac >ose.java * Execution: java >ose G * =ependencies: -td=ra.java * * Plots an G petal rose i G is odd0 and a 9G5petal rose i G is * even, usin# standard #rapics. *  *************************************************************************/

pu)lic class >ose +

pu)lic static void main-trin# ar#s0 +

int G A ;nte#er.parse;ntar#s60(  -td=ra.setscale5&, &0(  -td=ra.set7scale5&, &0(  -td=ra.setPenColor-td=ra.P;G<0(

  dou)le x6 A 6, y6 A 6(  or dou)le t A 6.6( t SA 86.6( t A 6.&0 +  dou)le teta A at.to>adianst0(  dou)le r A at.sinG * teta0(  dou)le x& A r * at.costeta0(  dou)le y& A r * at.sinteta0(  -td=ra.linex6, y6, x&, y&0(  x6 A x&(  y6 A y&(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 154/180

Banner.java

Below is the syntax highlighted version of Banner.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac Banner.java * Execution: java Banner s * =ependencies: -td=ra.java * * Plots te -trin# s, and moves it across te screen, let5to5ri#t, * rappin# around en it reaces te )order. * * $ java Banner "Hello, World" *

 *  *************************************************************************/

import java.at.Vont(

pu)lic class Banner +

pu)lic static void main-trin# ar#s0 +-trin# s A ar#s6(

  // remove te @$ )order  -td=ra.setscale&.6/99.6, 9&.6/99.60(  -td=ra.set7scale&.6/99.6, 9&.6/99.60(

  // set te ont  Vont A ne Vont"3rial", Vont.BL=, 60(  -td=ra.setVont0(  -td=ra.setPenColor-td=ra.WH;%E0(

  or dou)le i A 6.6( true( i A 6.6&0 +  -td=ra.clear-td=ra.BL3C<0(  -td=ra.texti $ &.60, 6.@, s0(  -td=ra.texti $ &.60 5 &.6, 6.@, s0(  -td=ra.texti $ &.60 &.6, 6.@, s0(  -td=ra.so60(  1

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

)layThatTune.java

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 155/180

Below is the syntax highlighted version of layThatTune.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Play%at%une.java * Execution: java Play%at%une S input.txt * =ependencies: -td3udio.java -td3udio.java * * %is is a data5driven pro#ram tat plays pure tones rom * te notes on te cromatic scale, speciied on standard input * )y teir distance rom concert 3. * * $ java Play%at%une S elise.txt * * * =ata iles

 * 5555555555 * ttp://.cs.princeton.edu/introcs/9&unction/elise.txt * ttp://.cs.princeton.edu/introcs/9&unction/DDlut)allons.txt * ttp://.cs.princeton.edu/introcs/9&unction/ree)ird.txt * ttp://.cs.princeton.edu/introcs/9&unction/3scale.txt * ttp://.cs.princeton.edu/introcs/9&unction/Gational[3ntem.txt * ttp://.cs.princeton.edu/introcs/9&unction/looney.txt * ttp://.cs.princeton.edu/introcs/9&unction/-tairay%oHeaven.txt * ttp://.cs.princeton.edu/introcs/9&unction/entertainer.txt * ttp://.cs.princeton.edu/introcs/9&unction/old5nassau.txt * ttp://.cs.princeton.edu/introcs/9&unction/ara)esFue.txt * ttp://.cs.princeton.edu/introcs/9&unction/irstcut.txt* ttp://.cs.princeton.edu/introcs/9&unction/tomsdiner.txt *

  *************************************************************************/

pu)lic class Play%at%une +

  pu)lic static void main-trin# ar#s0 +

  // repeat as lon# as tere are more inte#ers to read in  ile O-td;n.isEmpty00 +

  // read in te pitc, ere 6 A Concert 3 3?0  int pitc A -td;n.read;nt0(

  // read in duration in seconds

  dou)le duration A -td;n.read=ou)le0(

  // )uild sine ave it desired reFuency  dou)le Q A ??6 * at.po9, pitc / &9.60(  int G A int0 -td3udio.-3PLE[>3%E * duration0(  dou)le a A ne dou)leG&(  or int i A 6( i SA G( i0 +  ai A at.sin9 * at.P; * i * Q / -td3udio.-3PLE[>3%E0(  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 156/180

  // play it usin# standard audio  -td3udio.playa0(  1  11

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed 5ct 12 04"++"+3 ($) 2011.

pirograph.java

Below is the syntax highlighted version of 9#irogra#h.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac -piro#rap.java * Execution: java -piro#rap > r a * =ependencies: -td=ra.java * * =ra a curve ormed )y rollin# a smaller circle o radius r inside * a lar#er circle or radius >. ; te pen oset o te pen point in * te movin# circle is a, ten te eFuation o te resultin# curve * at time t is * * x A >r0*cost0 5 ra0*cos>r0/r0*t0 * y A >r0*sint0 5 ra0*sin>r0/r0*t0 * * $ java -piro#rap &K6 ?6 &@ *

 * $ java -piro#rap &66 @@ 96 * * Credits: idea su##ested )y =ie#o Gea) * >eerence: ttp://.mat.dartmout.edu/Rdlittle/java/-piroJrap * >eerence: ttp://.ordsmit.or#/Ranu/java/spiro#rap.tml *  *************************************************************************/

pu)lic class -piro#rap +

  pu)lic static void main-trin# ar#s0 +  dou)le > A =ou)le.parse=ou)lear#s60(  dou)le r A =ou)le.parse=ou)lear#s&0(  dou)le a A =ou)le.parse=ou)lear#s90(

  -td=ra.setscale5866, 8660(  -td=ra.set7scale5866, 8660(  -td=ra.clear-td=ra.BL3C<0(

  or dou)le t A 6.6( t S &66( t A 6.6&0 +  dou)le x A >r0 * at.cost0 5 ra0 * at.cos>r0/r0*t0(  dou)le y A >r0 * at.sint0 5 ra0 * at.sin>r0/r0*t0(  dou)le de#rees A 5at.to=e#rees>r0/r0*t(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 157/180

  -td=ra.picturex, y, "eart.#i", de#rees0(  // -td=ra.rotateat.to=e#rees>r0/r0*t0(  -td=ra.so960(  1

  1 1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Glo$8.java

Below is the syntax highlighted version of 5lo(2.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Cloc.java * Execution: java Cloc * =ependencies: -td=ra.java *  *************************************************************************/

pu)lic class Cloc +

pu)lic static void main-trin# ar#s0 +

or int t A 6( true( t0 +

  // remainder operator it dou)les so all ands move every second  dou)le seconds A t $ 6(  dou)le minutes A t / 6.60 $ 6(  dou)le ours A t / 866.60 $ &9(

  -td=ra.clear-td=ra.L;JH%[J>370(  -td=ra.setPen>adius0(

  // cloc ace  -td=ra.setPenColor-td=ra.BL3C<0(  -td=ra.illedCircle6.@, 6.@, 6.?@0(

  // our marers  -td=ra.setPenColor-td=ra.BL2E0(  or int i A 6( i S &9( i0 +  dou)le teta A at.to>adiansi * 860(  -td=ra.illedCircle6.@ 6.? * at.costeta0, 6.@ 6.? *at.sinteta0, .69@0(  1

  // second and

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 158/180

  -td=ra.setPen>adius.6&0(  -td=ra.setPenColor-td=ra.7ELLW0(  dou)le an#le& A at.to>adians * seconds0(  dou)le r& A 6.?(  -td=ra.line6.@, 6.@, 6.@ r& * at.sinan#le&0, 6.@ r& *at.cosan#le&00(

  // minute and  -td=ra.setPen>adius.690(  -td=ra.setPenColor-td=ra.J>370(  dou)le an#le9 A at.to>adians * minutes0(  dou)le r9 A 6.8(  -td=ra.line6.@, 6.@, 6.@ r9 * at.sinan#le90, 6.@ r9 *at.cosan#le900(

  // our and  -td=ra.setPen>adius.69@0(  -td=ra.setPenColor-td=ra.WH;%E0(  dou)le an#le8 A at.to>adians86 * ours0(  dou)le r8 A 6.9(

  -td=ra.line6.@, 6.@, 6.@ r8 * at.sinan#le80, 6.@ r8 *at.cosan#le800(

  // di#ital time  int second A t $ 6(  int minute A t / 60 $ 6(  int our A t / 8660 $ &9(  -trin# time A -trin#.ormat"$9d:$69d:$69d", our, minute,second0(  -td=ra.setPenColor-td=ra.B<[>E=0(  -td=ra.text6.@, 6.6, time0(

  // &666 miliseconds A & second  -td=ra.so&6660(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

s$illos$ope.java

Below is the syntax highlighted version of %s(illos(o#e.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac scilloscope.java * Execution: java scilloscope 3 B 7 pi pi7 * =ependencies: -td=ra.java *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 159/180

 * -imluate te output o an oscilloscope. 3ssume tat te vertical and * oriQontal inputs are sinusoidal. * * x A 3 sin pi0 * y A B sin 7 pi70 ** $ java scilloscope & & 9 8 96 ?@ *  *************************************************************************/

pu)lic class scilloscope +

  pu)lic static void main-trin# ar#s0 +  -td=ra.setscale5&, &0(  -td=ra.set7scale5&, &0(

  dou)le 3 A =ou)le.parse=ou)lear#s60( // amplitudes  dou)le B A =ou)le.parse=ou)lear#s&0(  dou)le A =ou)le.parse=ou)lear#s90( // an#ular reFuencies  dou)le 7 A =ou)le.parse=ou)lear#s80(

  dou)le pi A =ou)le.parse=ou)lear#s?0( // pase actors  dou)le pi7 A =ou)le.parse=ou)lear#s@0(

  // convert rom de#rees to radians  pi7 A at.to>adianspi0(  pi7 A at.to>adianspi70(

  or dou)le t A 6.6( t S &6( t A 6.666&0 +  dou)le x A 3 * at.sin * t pi0(  dou)le y A B * at.sin7 * t pi70(  -td=ra.pointx, y0(  -td=ra.so&60(  1

  1 1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Run%engthn$o#er.java

Below is the syntax highlighted version of un)ength@n(oder.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac >unLen#tEncoder.java * Execution: java >unLen#tEncoder S data.txt * =ependencies: -td;n.java *

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 160/180

 * >eads in a seFuence o 6!s and &!s and encodes usin# >LE. ** $ java >unLen#tEncoder * 6666&&&&6666&&&&& * ? ? ? @ *  *************************************************************************/

pu)lic class >unLen#tEncoder +

pu)lic static void main-trin# ar#s0 +car last A !6!(

  int count A 6(

  ile O-td;n.isEmpty00 +  car c A -td;n.readCar0(

  // ne line  i c AA !Zn!0 +  -ystem.out.println"" count0(

  count A 6(  last A !6!(  1

  // validate input  else i c OA !6!0 NN c OA !&!00  tro ne >untimeException";nvalid input"0(

  // repeated caracter  else i c AA last0 count(

  // can#es rom 6 to & or rom & to 6  else +  -ystem.out.printcount " "0(  count A &(  last A c(  1  1  -ystem.out.printlncount0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

lo!e.java

Below is the syntax highlighted version of >lo&e.java from §1.; In#ut and %ut#ut.

/*************************************************************************

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 161/180

 * Compilation: javac Jlo)e.java * Execution: java Jlo)e G * =ependencies: -td=ra.java * * Plots a #lo)e it an#le an#le. *  *************************************************************************/

pu)lic class Jlo)e +

pu)lic static void main-trin# ar#s0 +dou)le alpa A =ou)le.parse=ou)lear#s60(

  -td=ra.set7scale5&, &0(  -td=ra.setscale5&, &0(  -td=ra.setPenColor-td=ra.BL2E0(

  dou)le x6 A &, y6 A 6(  or dou)le t A 6.6( t SA 96 * 86.6( t A 6.&0 +  dou)le teta A at.to>adianst0(  dou)le r A at.cosalpa * teta0(

dou)le x& A r * at.costeta0(  dou)le y& A r * at.sinteta0(  -td=ra.linex6, y6, x&, y&0(  x6 A x&(  y6 A y&(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Ran#omTe't.java

Below is the syntax highlighted version of andomText.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac >andom%ext.java * Execution: java >andom%ext s G * =ependencies: -td=ra.java * * Plots te -trin# s, G times at random locations, and in random * colors. * * $ java >andom%ext Hello &6 * * $ java >andom%ext World &@ * * $ java >andom%ext Uava 96

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 162/180

 * *  *************************************************************************/

import java.at.Color(import java.at.Vont(

pu)lic class >andom%ext +

pu)lic static void main-trin# ar#s0 +-trin# s A ar#s6(

  int G A ;nte#er.parse;ntar#s&0(  -td=ra.clearColor.BL3C<0(  Vont A ne Vont"3rial", Vont.BL=, 60(  -td=ra.setVont0(

  or int i A 6( i S G( i0 +  -td=ra.setPenColorColor.#etH-BColorloat0 at.random0, &.6,&.600(  dou)le x A at.random0(

  dou)le y A at.random0(  -td=ra.textx, y, s0(  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Ran#om+al8.java

Below is the syntax highlighted version of andomWal2.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac >andomWal.java * Execution: java >andomWal G * =ependencies: -td=ra.java * * $ java >andomWal 96 * total steps A 866 * * $ java >andomWal @6 * total steps A 986 * * -imulates a 9= random al and plots te trajectory. * * >emars: ors )est i G is a divisor o 66. *  *************************************************************************/

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 163/180

pu)lic class >andomWal +

pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(  -td=ra.setscale5G, G0(  -td=ra.set7scale5G, G0(  -td=ra.clear-td=ra.J>370(

  int x A 6, y A 6(  int steps A 6(  ile at.a)sx0 S G NN at.a)sy0 S G0 +  -td=ra.setPenColor-td=ra.WH;%E0(  -td=ra.illed-Fuarex, y, 6.?@0(  dou)le r A at.random0(  i r S 6.9@0 x55(  else i r S 6.@60 x(  else i r S 6.'@0 y55(  else i r S &.660 y(  steps(  -td=ra.setPenColor-td=ra.BL2E0(

  -td=ra.illed-Fuarex, y, .?@0(  -td=ra.so?60(  1  -ystem.out.println"%otal steps A " steps0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Ballisti$6otion.java

Below is the syntax highlighted version of Ballisti(?otion.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac Ballisticotion.java * Execution: java Ballisticotion v teta * =ependencies: -td=ra.java * * -imluate te motion o a )all ired it velocity v at teta de#rees * it coeicient o dra# C. 2ses Euler5Cramer metod to numerically * solve dierential eFuation. ** $ java Ballisticotion &K6.6 6.6 * * $ java Ballisticotion 96.6 [email protected] *  *************************************************************************/

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 164/180

pu)lic class Ballisticotion +

  pu)lic static void main-trin# ar#s0 +  dou)le J A D.K( // #ravitational constant m/sT9  dou)le C A 6.669( // dra# orce coeicient

  dou)le v A =ou)le.parse=ou)lear#s60( //velocity  dou)le teta A at.to>adians=ou)le.parse=ou)lear#s&00( // an#lein radians

  dou)le x A 6.6, y A 6.6( // position  dou)le vx A v * at.costeta0( // velocity in x direction  dou)le vy A v * at.sinteta0( // velocity in y direction

  dou)le ax A 6.6, ay A 6.6( // acceleration  dou)le t A 6.6( // time  dou)le dt A 6.6&( // time Fuantum

  dou)le max> A v*v / J( // maximum distance itout dra#

orce-td=ra.setscale6, max>0(

  -td=ra.set7scale6, max>0( // set te same as or 5scale

  // loop until )all its #round  ile y MA 6.60 +  v A at.sFrtvx*vx vy*vy0(  ax A 5C * v * vx(  ay A 5J 5 C * v * vy(  vx A ax * dt(  vy A ay * dt(  x A vx * dt(  y A vy * dt(  -td=ra.illedCirclex, y, 6.9@0(  -td=ra.so@0(  1  -td=ra.so0(  1 1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )!e Sep 1'"0"+0 ($) 201.

Heart.java

Below is the syntax highlighted version of Heart.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Heart.java

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 165/180

 * Execution: java Heart * =ependencies: -td=ra.java * * =ra a pin eart a illed diamond plus to illed circles0. *  *************************************************************************/

pu)lic class Heart +  pu)lic static void main-trin# ar#s0 +  -td=ra.setscale5&.@, &.@0(  -td=ra.set7scale5&.@, &.@0(  -td=ra.setPenColor-td=ra.P;G<0(

  // dra diamond  dou)le xs A + 5&, 6, &, 6 1(  dou)le ys A + 6, 5&, 6, & 1(  -td=ra.illedPoly#onxs, ys0(

  // circles  -td=ra.illedCircle6.@, 6.@, & / at.sFrt900(

  -td=ra.illedCircle56.@, 6.@, & / at.sFrt900(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

6a#ness.java

Below is the syntax highlighted version of ?adness.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac adness.java * Execution: java adness ** Plots a parametric i#ure ic 3. <. =edney reers to as * iller!s adness. * * >eerence: %e a#ic acine )y 3. <. =edney. %is i#ure * as desi#ned )y -tanley -. iller, a mana#ement consultant. * *  *************************************************************************/

pu)lic class adness +

  pu)lic static void main-trin# ar#s0 +  -td=ra.setscale5&.', &.'0(  -td=ra.set7scale5&.&, &.&0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 166/180

  dou)le x6 A 56.', y6 A &.6(  or dou)le t A 6.6( true( t A 6.6&0 +  dou)le x& A at.sin6.DD*t0 5 6.'*at.cos8.6&*t0(  dou)le y& A at.cos&.6&*t0 6.&*at.sin&@.68*t0(  -td=ra.linex6, y6, x&, y&0(  x6 A x&(  y6 A y&(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

ButterLy.java

Below is the syntax highlighted version of Butterfly.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac Butterly.java * Execution: java Butterly * =ependencies: -td=ra.java ** Plots a )utterly5lie curve. * * >eerence: 3. <. =edney!s %e a#ic acine. Credited to * %emple H. Vay o te 2niversity o -outern ississippi. *

  *************************************************************************/

pu)lic class Butterly +

  pu)lic static void main-trin# ar#s0 +  -td=ra.setscale5?, ?0(  -td=ra.set7scale5?, ?0(  dou)le x6 A 6, y6 A 6(  or dou)le teta A 6.6( teta S '9( teta A 6.6&0 +  dou)le r A at.expat.costeta00 5 9*at.cos?*teta0 at.poat.sinteta/&90, @0(  dou)le x& A r * at.costeta0(  dou)le y& A r * at.sinteta0(  -td=ra.linex6, y6, x&, y&0(  x6 A x&(  y6 A y&(  1  11

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 167/180

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

tu#ents.java

Below is the syntax highlighted version of 9tudents.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac -tudents.java * Execution: java -tudents S students.txt * =ependencies: -td;n.java * -ample data: ttp://introcs.cs.princeton.edu/&@inout/students.txt * * >eads in te inte#er G rom standard input, ten a list * o G student records, ere eac record consists o our * ields, separated )y itespace:

 * 5 irst name * 5 last name * 5 email address * 5 ic section tey!re in * * %en, print out a list o email address o students in section ? and @. * * $ &86 * -ara Wan# tan# ' * 3ustin %aylor actaylor & * =avid >osner drosner ? * >e)ecca 3llen re)eccaa ' * >ajiv 3yyan#ar ayyan#ar ' * =aniel Barrett dr)arret K * Gic Byrd n)yrd ' * Emily Capra ecapra K * Uonny Clore jclore ' * ... * * $ -ection ? * 555555555 * drosner * jcarles * jp * mlampert * ... *

 * -ection @ * 555555555 * #ian * a#roQdan * aj * aornell * ... *  *************************************************************************/

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 168/180

pu)lic class -tudents +  pu)lic static void main-trin# ar#s0 +

// read te num)er o students  int G A -td;n.read;nt0(

  // initialiQe our parallel arrays  -trin# irst A ne -trin#G(  -trin# last A ne -trin#G(  -trin# email A ne -trin#G(  int section A ne intG(

  // read in te data  or int i A 6( i S G( i0 +  irsti A -td;n.read-trin#0(  lasti A -td;n.read-trin#0(  emaili A -td;n.read-trin#0(  sectioni A -td;n.read;nt0(  1

  // print email addresses o all students in section ?  -tdut.println"-ection ?"0(  -tdut.println"555555555"0(  or int i A 6( i S G( i0 +  i sectioni AA ?0 +  -tdut.printlnemaili0(  1  1  -tdut.println0(

  // print email addresses o all students in section @  -tdut.println"-ection @"0(  -tdut.println"555555555"0(  or int i A 6( i S G( i0 +  i sectioni AA @0 +  -tdut.printlnemaili0(  1  1

  1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" )!e #eb 1' 11"'4"+0 (S) 2011. huMe.java

Below is the syntax highlighted version of 9huffle.java from §1.; In#ut and %ut#ut.

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 169/180

/************************************************************************* * Compilation: javac -ule.java * Execution: java -ule G S caliornia5#ov.txt * =ependencies: -td;n.java ** >eads in G lines o text, sules tem, and print tem in random order. * 2ses <nut!s sulin# sule. * * %e ile caliornia5#ov.txt contains a list o te &8@ * candidates in te cto)er ', 9668 Caliornia #overnor!s runo * election. %e ile cards.txt contains a list o @9 playin# cards. * * * $ java -ule @ S caliornia5#ov.txt * ;ris 3dam * =ou#las 3nderson * 3lex5-t. Uames * 3n#elyne * Brooe 3dams

 * * $ java -ule @ S cards.txt * Vour o Clu)s * -ix o Clu)s * %ree o Clu)s * =euce o Clu)s * Vive o Clu)s * *  *************************************************************************/

pu)lic class -ule +

// saps array elements i and j  pu)lic static void exc-trin# a, int i, int j0 +  -trin# sap A ai(  ai A aj(  aj A sap(  1

  // tae as input an array o strin#s and rearran#e tem in random order  pu)lic static void sule-trin# a0 +  int G A a.len#t(  or int i A 6( i S G( i0 +  int r A i int0 at.random0 * G5i00( // )eteen i and G5&  exca, i, r0(  1

  1

  // tae as input an array o strin#s and print tem out to standard output  pu)lic static void so-trin# a0 +  or int i A 6( i S a.len#t( i0 +  -ystem.out.printlnai0(  1  1

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 170/180

  pu)lic static void main-trin# ar#s0 +int G A ;nte#er.parse;ntar#s60(

  -trin# a A ne -trin#G(

  // read in data  or int i A 6( i S G( i0 +  ai A -td;n.readLine0(  1

  // sule array and print permutation  sulea0(  soa0(

  -ystem.out.println0(

  // do it a#ain  sulea0(  soa0(

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Reverse.java

Below is the syntax highlighted version of everse.java from §1.; In#ut and %ut#ut. 

/************************************************************************* * Compilation: javac >everse.java -td;n.java * Execution: java >everse ** >eads in real num)ers and prints tem in reverse order. 2ses an * array and repeatedly dou)les its siQe i necessary. * * $ java >everse * &.6 9.6 8.6 ?.6 @.6 .6 @.D @.K @.' * SCtrl5dM* @.' @.K @.D .6 @.6 ?.6 8.6 9.6 &.6* * Windos users: use SCtrl5QM instead o SCtrl5dM to si#niy EV. *  *************************************************************************/

class >everse +  pu)lic static void main-trin# ar#s0 +  int G A 6( // num)er o elements in array  dou)le data A ne dou)le&( // initialQe array capacity A &

  ile O-td;n.isEmpty00 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 171/180

  // dou)le te siQe o te array i necessary  i G AA data.len#t0 +  dou)le temp A ne dou)le9*G(  or int i A 6( i S G( i0 tempi A datai(  data A temp(  1

  // read in te next value  dataG A -td;n.read=ou)le0(  1

  // print it out  or int i A G5&( i MA 6( i550  -ystem.out.printdatai " "0(  -ystem.out.println0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Golli#ingBalls.java

Below is the syntax highlighted version of 5ollidingBalls.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac Collidin#Balls.java

 * Execution: java Collidin#Balls G * =ependencies: -td=ra.java * * -imulate G )alls o uniorm mass, )ouncin# o te our alls * and eac oter accordin# to te las o elastic collisions. * * $ java Collidin#Balls @6 * * Limitations * 55555555555 * 5 ;neicient since it perorms GT9 collision cecs per dt. * * 5 Can miss collisions. 2se event5)ased simulation and a priority * Fueue instead o time5)ased simulation to ix. * * 5 pysics not correct *  *************************************************************************/

import java.at.Color(

pu)lic class Collidin#Balls +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 172/180

  pu)lic static void main-trin# ar#s0 +  int G A ;nte#er.parse;ntar#s60(  dou)le dt A &.6(  dou)le >3=;2- A @.6(

  // initialiQe positions and velocities at random  dou)le px A ne dou)leG(  dou)le py A ne dou)leG(  dou)le vx A ne dou)leG(  dou)le vy A ne dou)leG(  Color color A ne ColorG(  or int i A 6( i S G( i0 +  pxi A & ?K6 * at.random0(  pyi A & ?K6 * at.random0(  vxi A &6 * at.random0 5 @(  vyi A &6 * at.random0 5 @(  colori A Color.#etH-BColorloat0 at.random0, &.6, &.60(  1

  int -;^E A @&9(  -td=ra.setscale6, -;^E0(  -td=ra.set7scale6, -;^E0(

  ile true0 +  -td=ra.clearColor.BL3C<0(

  // detect collision it all and reverse velocity  or int i A 6( i S G( i0 +  i pxi dt * vxi M -;^E 5 >3=;2-0 pxi dt *vxi S >3=;2-00 vxi A 5vxi(  i pyi dt * vyi M -;^E 5 >3=;2-0 pyi dt *vyi S >3=;2-00 vyi A 5vyi(  1

  // detect collision it oter particles  or int i A 6( i S G( i0 +  or int j A i &( j S G( j0 +  dou)le dx A pxi 5 pxj0 dt * vxi 5 vxj0(  dou)le dy A pyi 5 pyj0 dt * vyi 5 vyj0(

  // i collision sap velocities  i at.sFrtdx*dx dy*dy0 SA 9*>3=;2-0 +  dou)le tempx A vxi(  dou)le tempy A vyi(  vxi A vxj(  vyi A vyj(

  vxj A tempx(  vyj A tempy(  -td3udio.play"pop.av"0(  )rea( // only pairise collisions  1  1  1

  // update positions  or int i A 6( i S G( i0 +

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 173/180

  pxi A pxi vxi * dt(  pyi A pyi vyi * dt(  1

  // update positions  or int i A 6( i S G( i0 +  -td=ra.setPenColorcolori0(  -td=ra.illedCirclepxi, pyi, >3=;2-0(  1  -td=ra.so@60(  1  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

Du8e.java

Below is the syntax highlighted version of $u2e.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac =ue.java * Execution: java =ue * =ependencies: -td=ra.java -td;n.java * * =ra te seFuence o ima#es %&.#i to %&'.#i. %is creates * te illusion o motion, ere te Uava mascot =ue cart5eels

 * across te screen. * * >eerence:ttp://java.sun.com/docs/)oos/tutorial/uisin#/components/example5&dot?/index.tmlY%um)le;tem *  *************************************************************************/

pu)lic class =ue +

  pu)lic static void main-trin# ar#s0 +  int ima#es A &'( // num)er o ima#es  int W;=%H A &86, HE;JH% A K6( // ima#es are &865)y5K6  -td=ra.setCanvas-iQeW;=%H, HE;JH%0(  -td=ra.setscale6, W;=%H0(  -td=ra.set7scale6, HE;JH%0(

  // main animation loop  or int t A 6( true( t0 +  int i A & t $ ima#es0(  -trin# ilename A "%" i ".#i"( // name o te it ima#e  -td=ra.pictureW;=%H/9.6, HE;JH%/9.6, ilename0(  -td=ra.so&660(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 174/180

  1  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne. Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

6oreDu8e.java

Below is the syntax highlighted version of ?ore$u2e.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac ore=ue.java * Execution: java ore=ue * =ependencies: -td=ra.java -td;n.java %&5&'.#i * * ae =ue carteel across te screen rom ri#t to let, rappin# * around. * * >eerence:ttp://java.sun.com/docs/)oos/tutorial/uisin#/components/example5&dot?/index.X *  *************************************************************************/

pu)lic class ore=ue +

  pu)lic static void main-trin# ar#s0 +  // ima#e idt A &865)y5K6  int ;3JE- A &'( // ima#es per carteel  int C3>%WHEEL- A @( // carteels per cycle  int C7CLE- A &66( // num)er o cycles  int ]E>L3P A @'( // overlap )eteen tocarteels  int W;=%H A ]E>L3P * C3>%WHEEL-( // idt o te indo  int HE;JH% A K6( // ei#t o te indo  -td=ra.setCanvas-iQeW;=%H, HE;JH%0(  -td=ra.setscale6, W;=%H0(  -td=ra.set7scale6, HE;JH%0(

  // main animation loop  int x A W;=%H * C7CLE-(  or int t A 6( t S C7CLE-( t0 +  x 5A ]E>L3P(  or int i A &( i SA ;3JE-( i0 +  -td=ra.clear0(  -trin# ilename A "%" i ".#i"( // name o it ima#e  -td=ra.picture x $ W;=%H, HE;JH%/9.6, ilename0(  -td=ra.pictureW;=%H x $ W;=%H, HE;JH%/9.6, ilename0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 175/180

  -td=ra.so&660(  1  -td=ra.so&6660(  1

  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

"uestionsT,enty.java

Below is the syntax highlighted version of 'uestionsTwenty.java from §1.; In#ut and %ut#ut.

/************************************************************************* * Compilation: javac Iuestions%enty.java * Execution: java Iuestions%enty * =ependencies -td;n.java * * %in o an inte#er )eteen 6 and &666666. * %rutully anser !true! or !alse! to eac Fuestion ; as. * * I&: ;s your num)er SA @666664 * true

 * I9: ;s your num)er SA 9@66664 * true * I8: ;s your num)er SA &9@6664 * true * I?: ;s your num)er SA 9@664 * alse * I@: ;s your num)er SA D8'@64 * true * I: ;s your num)er SA 'K&9@4 * alse * I': ;s your num)er SA K@D8K4 * true * IK: ;s your num)er SA K96894 * true * ID: ;s your num)er SA K66'D4 * alse * I&6: ;s your num)er SA K&6@4 * true * I&&: ;s your num)er SA K6@K4 * true * I&9: ;s your num)er SA K689?4 * alse * I&8: ;s your num)er SA K6??4

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 176/180

 * true * I&?: ;s your num)er SA K68K@4 * true * I&@: ;s your num)er SA K68@@4 * true * I&: ;s your num)er SA K68?64 * alse * I&': ;s your num)er SA K68?K4 * true * I&K: ;s your num)er SA K68??4 * true * I&D: ;s your num)er SA K68?94 * true * I96: ;s your num)er SA K68?&4 * alse * * 7our inte#er is K68?9. *  *************************************************************************/

pu)lic class Iuestions%enty +

  pu)lic static void main-trin# ar#s0 +  int lo A 6, i A &666666(  -ystem.out.println"%in o an inte#er )eteen " lo " and " i "."0(  -ystem.out.println"%rutully anser !true! or !alse! to eacFuestion ; as."0(  -ystem.out.println0(

  or int i A &( lo S i( i0 +

  // invariant: num)er must )e in te interval lo, i  int mid A lo i 5 lo0 / 9(  -ystem.out.print"I" i ": "0(  -ystem.out.println";s your num)er SA " mid "4"0(  )oolean response A -td;n.readBoolean0(  i response0 i A mid(  else lo A mid &(  1

  -ystem.out.println"7our inte#er is " lo "."0(  -ystem.out.println0(  1

1

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

A##.java

Below is the syntax highlighted version of Add.java from §1.; In#ut and %ut#ut. 

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 177/180

/************************************************************************* * Compilation: javac 3dd.java * Execution: java 3dd

 * =ependencies: -td;n.java ** Prompts te user or to inte#ers num)ers, reads tem in rom standard * input, and prints out teir sum. * * Gote: you must av te ile -td;n.java in your orin# directory. * * $ java 3dd * %ype te irst inte#er * @ S55 user types tis * %ype te second inte#er * 88 S55 user types tis * %eir sum is 8K

 *  *************************************************************************/

pu)lic class 3dd +  pu)lic static void main-trin# ar#s0 +

  // prompt user or irst inte#er and read rom standard input  -tdut.println"%ype te irst inte#er"0(  int x A -td;n.read;nt0(

  // prompt user or second inte#er and read rom standard input  -tdut.println"%ype te second inte#er"0(  int y A -td;n.read;nt0(

  // compute sum and print to standard output  int sum A x y(  -tdut.println"%eir sum is " sum0(  11

Copyright © 2000–2010, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" Wed #eb 3 03"02"0% (S) 2011.

 Transition.java

Below is the syntax highlighted version of Transition.java from §1.C 5ase 9tudy3 agean2 .

/************************************************************************* * Compilation: javac %ransition.java * Execution: java %ransition S input.txt

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 178/180

 * =ata iles: ttp://introcs.cs.princeton.edu/&pa#eran/tiny.txt * ttp://introcs.cs.princeton.edu/&pa#eran/medium.txt * * %is pro#ram is a ilter tat reads lins rom standard input and * produces te correspondin# transition matrix on standard output. * Virst, it processes te input to count te outlins rom eac pa#e. * %en it applies te D65&6 rule to compute te transition matrix. * ;t assumes tat tere are no pa#es tat ave no outlins in te * input see Exercise &..80. * * $ more tiny.txt * @* 6 &* & 9 & 9* & 8 & 8 & ?* 9 8* 8 6* ? 6 ? 9* * $ java %ransition S tiny.txt

 * @ @ * 6.69 6.D9 6.69 6.69 6.69 * 6.69 6.69 6.8K 6.8K 6.96 * 6.69 6.69 6.69 6.D9 6.69 * 6.D9 6.69 6.69 6.69 6.69 * 6.?' 6.69 6.?' 6.69 6.69 *  *************************************************************************/

pu)lic class %ransition +

  pu)lic static void main-trin# ar#s0 +

  int G A -td;n.read;nt0( // num)er o pa#es  int counts A ne intGG( // countsij A Y lins rom pa#ei to pa#e j  int out=e#ree A ne intG( // out=e#reei A Y lins rom pa#ei to anyere

  // 3ccumulate lin counts.ile O-td;n.isEmpty00 +

  int i A -td;n.read;nt0(int j A -td;n.read;nt0(out=e#reei(countsij(

1-tdut.printlnG " " G0(

// Print pro)a)ility distri)ution or ro i.or int i A 6( i S G( i0 +

  // Print pro)a)ility or column j.or int j A 6( j S G( j0 +

  dou)le p A .D6*countsij/out=e#reei .&6/G(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 179/180

  -tdut.print"$'.@ ", p0(1-tdut.println0(

11

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

 Lat !pdated" S!n 5ct & 02"2&"2 ($) 201.

Ran#omurfer.java

Below is the syntax highlighted version of andom9urfer.java from §1.C 5ase 9tudy3 agean2 .

/************************************************************************* * Compilation: javac >andom-urer.java * Execution: java >andom-urer % * =ata iles: ttp://introcs.cs.princeton.edu/&pa#eran/tiny.txt * ttp://introcs.cs.princeton.edu/&pa#eran/medium.txt * * $ java %ransition S tiny.txt java >andom-urer &666666 * 6.9'9D' 6.9@K8 6.&?@DK 6.9?'9D 6.6'D8 *  *************************************************************************/

pu)lic class >andom-urer +  pu)lic static void main-trin# ar#s0 +

  int % A ;nte#er.parse;ntar#s60( // num)er o moves  int A -td;n.read;nt0( // num)er o pa#es 5 i#noresince A G  int G A -td;n.read;nt0( // num)er o pa#es

  // >ead transition matrix.  dou)le p A ne dou)leGG( // pij A pro). tat surermoves rom pa#e i to pa#e j  or int i A 6( i S G( i0  or int j A 6( j S G( j0

pij A -td;n.read=ou)le0(

int reF A ne intG( // reFi A Y times surer itspa#e i 

// -tart at pa#e 6.int pa#e A 6(

  or int t A 6( t S %( t0 +

  // ae one random move.dou)le r A at.random0(

8/9/2019 Chapter 1 Programing

http://slidepdf.com/reader/full/chapter-1-programing 180/180

  dou)le sum A 6.6(or int j A 6( j S G( j0 +

  // Vind interval containin# r.sum A ppa#ej(i r S sum0 + pa#e A j( )rea( 1

1reFpa#e(

1

// Print pa#e rans.or int i A 6( i S G( i0 +

  -tdut.print"$K.@", dou)le0 reFi / %0(1

  -tdut.println0(1

1

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Lat !pdated" #ri /!g ' 03"2&"+' ($) 2011.