prog patterns

Upload: nitish-pathak

Post on 07-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Prog Patterns

    1/9

    Mehran Sahami Handout #11

    CS 106A October 5, 2007

    Simple Programming PatternsBased on a handout by Eric Roberts

    This handout summarizes some of the most common programming patterns that you will

    encounter in Java. Each of these patterns is covered in more detail in Chapters 2, 3, or 4of the textbook, but it's good to have them in a simple handy reference as well.

    The first set of patterns involves getting data in and out of the computer, which provide

    the necessary support for the input and output phases of a typical programming task. The

    patterns you use depend on the type of value, as shown in the following table:

    7\SH 'HFODUDWLRQ ,QSXWSDWWHUQInteger LQWYDUYDOXH YDUUHDG,QWSURPSWFloating-point GRXEOHYDUYDOXH YDUUHDG'RXEOHSURPSWString 6WULQJYDUYDOXH YDUUHDG/LQHSURPSW

    The following patterns are useful in calculations:

    (QJOLVK -DYDORQJIRUP -DYDVKRUWKDQGIRUPAdd \ to [. [[\ [\

    Subtract \ from[. [[\ [\Add 1 to [ (increment [). [[ [

    Subtract 1 from[ (decrement [). [[ [The most helpful patterns, however, encompass programming operations on a larger scale

    and help you establish the overall strategy of a program. The most important ones aredescribed in the next few sections.

    7KHUHSHDW1WLPHVSDWWHUQ(page 101)This pattern is the same as it was in Karel and is used for the same purpose.

    IRULQWLL1L^VWDWHPHQWVWREHUHSHDWHG

    `In Java, however, you are allowed to use the value of the index variable L in the body of

    the loop.

    7KHUHDGXQWLOVHQWLQHOSDWWHUQ(page 102)This pattern is useful whenever you need to read in values until the user enters a

    particular value to signal the end of input. Such values are called VHQWLQHOV.

    ZKLOHWUXH^SURPSWXVHUDQGUHDGLQDYDOXHLIYDOXHVHQWLQHOEUHDNUHVWRIERG\

    `

    http://technicalsupportindia.blogspot.com/

  • 8/6/2019 Prog Patterns

    2/9

    1ILVER7ELEQM ,ERHSYX!'7% 3GXSFIV!

    'SRXVSP7XEXIQIRXW!&EWIHSRELERHSYXF])VMG6SFIVXW !

    !

    8LMWLERHSYXSJJIVWWSQIEHHMXMSREPRSXIWSR.EZEtWGSRXVSPWXEXIQIRXWHIWGVMFIHQSVI !

    JYPP] MR 'LETXIV SJ XLI XI\XFSSO XLEX IQTLEWM^I XLI MQTSVXERX GSRGITXW -X EPWS!

    HIWGVMFIWETVSKVEQQMRKTVSFPIQQEOMRKYWISJZEVMSYWGSRXVSPWXVYGXYVIW !!

    8S[VMXITVSKVEQW]SYRIIHXSYRHIVWXERHGSRXVSPWXEXIQIRXWJVSQX[STIVWTIGXMZIW]SY !

    QYWX LEZI E LSPMWXMG WIRWI SJ [LIR XS YWI XLIQERH [L] FYX ]SYQYWX EPWS PIEVR XS!

    YRHIVWXERHXLIVIHYGXMSRMWXMGHIXEMPW *SVXLMWFMKTMGXYVITIVWTIGXMZI ]SYGER VIP] XSE!PEVKII\XIRXSR]SYVI\TIVMIRGIJVSQ/EVIP !!

    d -J]SY[ERXXSXIWXEGSRHMXMSRXLEXVIUYMVIWER!MJ!WXEXIQIRXMR/EVIP]SYRIIHXLI!MJ!

    WXEXIQIRXMR.EZE !

    d -J]SY[SYPH YWIXLI![LMPI!SV!JSV!WXEXIQIRX MR/EVIP ]SY[MPP TVIWYQEFP] YWI XLI!WEQIWXEXIQIRXJSVQMR.EZE !

    !

    8LISXLIVLSPMWXMGTSMRXXLEXMWIWWIRXMEPEFSYXGSRXVSPWXEXIQIRXWMWXLEXXLIGSRXVSPPMRI !

    MWGSRGITXYEPP]MRHITIRHIRXJVSQXLIFSH]8LYWMJ]SYWIIEGSRWXVYGXPMOI !!

    JSVMRXM!MM_! ! 'SRXVSPPMRI!! WXEXIQIRXW! ! &SH]!a!

    !

    XLI WXEXIQIRXW MRXLI FSH][MPPFIVITIEXIHJSVIEGLSJXLIZEPYIWSJ!M!JVSQXS-X!

    HSIWRtXQEXXIVEXEPP[LEXXLSWIWXEXIQIRXWEVI !

    !&SSPIERHEXE!

    %RSXLIVMQTSVXERXXSTMGMWXLEXSJXLIHEXEX]TI!FSSPIER[LMGLMWXLIQIERWF][LMGL!

    .EZE TVSKVEQWEWO UYIWXMSRW -R/EVIP XLI GSYRXIVTEVXW XS!FSSPIER!EVI XLI GSRHMXMSRW!

    WYGL EW! JVSRX-W'PIEV! SV! FIITIVW4VIWIRX -R .EZE XLI VERKI SJ EZEMPEFPI!

    GSRHMXMSRWMWQYGLVMGLIVERHMRZSPZIWXLIVIPEXMSREPSTIVEXSVWERHXLIPSKMGEPSTIVEXSVW !

    FSXLGSZIVIHSRTEKISJXI\XFSSO8LIQSWXMQTSVXERXPIWWSRWXSXEOIJVSQXLIWI!

    WIGXMSRWEVI!!

    d ;EXGL SYX JSVGSRJYWMRK!!! EWWMKRQIRX [MXL!!!! IUYEPMX] 8LMW JIEXYVI SJ WIZIVEP!

    TVSKVEQQMRKPERKYEKIWMRGPYHMRK''ERH.EZELEWTVSFEFP]GEYWIHQSVIFYKW!

    XLERER]SXLIV!d &IGEVIJYPXSYRHIVWXERHFSXLXLIMRXIVTVIXEXMSRERHXLIIZEPYEXMSRSVHIVSJXLIPSKMGEP!

    STIVEXSVW!!ERH!``!SVERH!!RSX!!

    8LIXMQI]SYTYXMRXSQEOMRKWYVI]SYYRHIVWXERH !FSSPIER!HEXERS[[MPPTE]JSVMXWIPJ!

    QER]XMQIWSZIV[LIRXLITVSKVEQWKIXQSVIGSQTPMGEXIHPEXIVMRXLIUYEVXIV !!

    !

    http://technicalsupportindia.blogspot.com/

    http://technicalsupportindia.blogspot.com/
  • 8/6/2019 Prog Patterns

    3/9

    ! ii!

    'LIGOIVFSEVHTVSFPIQ!

    'VIEXIE!+VETLMGW4VSKVEQ!WYFGPEWWXLEXHVE[WEGLIGOIVFSEVHMRXLIKVETLMGW[MRHS[ !

    8LIRYQFIVSJVS[WERHGSPYQRWEVIKMZIRF]XLIREQIHGSRWXERXW !263;7!ERH!2'309127!

    ERHXLIWUYEVIWWLSYPHFIWM^IHWSXLEXXLI]JMPPXLIZIVXMGEPWTEGI*SVI\EQTPIMJ!263;7!

    ERH!2'309127

    !EVIFSXLVYRRMRKXLMWTVSKVEQWLSYPHTVSHYGIXLIJSPPS[MRKSYXTYX

    !!

    !!

    +VETLMGWPMFVEV]HSGYQIRXEXMSR!

    8LI!NEZEHSG!HSGYQIRXEXMSRJSVXLI%'1PMFVEVMIWMWEZEMPEFPIYRHIVXLIq0MROWrWIGXMSR!

    SJXLI'7%LSQITEKI%PWSXLIQIXLSHWMR*MKYVI[MPPLIPT[MXLXLIEWWMKRQIRX !!

    *MKYVI7SQIYWIJYPQIXLSHWMREGQKVETLMGW !

    'SRWXVYGXSVW!! RI[+0EFIP7XVMRKXI\X! SV! RI[+0EFIP7XVMRKXI\XHSYFPI\HSYFPI] !

    'VIEXIWERI[!+0EFIP!SFNIGXXLIWIGSRHJSVQWIXWMXWPSGEXMSREW[IPP !! RI[+6IGXHSYFPI\HSYFPI]HSYFPI[MHXLHSYFPILIMKLX !

    'VIEXIWERI[!+6IGX!SFNIGXXLI!\!ERH!]!TEVEQIXIVWGERFISQMXXIHERHHIJEYPXXS !

    ! RI[+3ZEPHSYFPI\HSYFPI]HSYFPI[MHXLHSYFPILIMKLX !

    'VIEXIWERI[!+3ZEP!SFNIGXXLI!\!ERH!]!TEVEQIXIVWGERFISQMXXIHERHHIJEYPXXS !!

    ! RI[+0MRIHSYFPI\HSYFPI]HSYFPI\HSYFPI] !'VIEXIWERI[!+0MRI!SFNIGXGSRRIGXMRK\!]ERH\!]!

    !

    1IXLSHWGSQQSRXSEPPKVETLMGEPSFNIGX!! ZSMHWIX0SGEXMSRHSYFPI\HSYFPI]!

    7IXWXLIPSGEXMSRSJXLMWSFNIGXXSXLIWTIGMJMIHGSSVHMREXIW !!

    ! ZSMHQSZIHSYFPIH\HSYFPIH]!

    1SZIWXLISFNIGXYWMRKXLIHMWTPEGIQIRXW !H\!ERH!H]!!

    ! HSYFPIKIX;MHXL!

    6IXYVRWXLI[MHXLSJXLISFNIGX !!

    ! HSYFPIKIX,IMKLX!

    6IXYVRWXLILIMKLXSJXLISFNIGX !!

    ! ZSMHWIX'SPSV'SPSVG!

    7IXWXLIGSPSVSJXLISFNIGX !!

    1IXLSHWEZEMPEFPIJSV+6IGXERH+3ZEPSRP]!ZSMHWIX*MPPIHFSSPIERJMPP!

    7IXW[LIXLIVXLMWSFNIGXMWJMPPIH XVYI!QIERWJMPPIH!JEPWI!QIERWSYXPMRIH!FSSPIERMW*MPPIH!

    6IXYVRW!XVYI!MJXLISFNIGXMWJMPPIH !ZSMHWIX*MPP'SPSV'SPSVG!

    7IXWXLIGSPSVYWIHXSJMPPXLMWSFNIGX-JXLIGSPSVMW !RYPPJMPPMRKYWIWXLIGSPSVSJXLISFNIGX !

    1IXLSHWEZEMPEFPIJSV+0EFIPSRP]!! ZSMHWIX*SRX7XVMRKJSRX2EQI!

    7IXWXLIJSRXEWHIWGVMFIHMR'LETXIV !!

    ! HSYFPIKIX%WGIRX!

    6IXYVRWXLILIMKLXEFSZIXLIFEWIPMRI !!

    ! ! !

    YRHIVXLIq0MROWrWIGXMSR!

    http://technicalsupportindia.blogspot.com/

  • 8/6/2019 Prog Patterns

    4/9

    ! ii!

    7SPYXMSRXSXLI'LIGOIVFSEVHTVSFPIQ!

    !! !

    !! *MPI'LIGOIVFSEVHNEZE!

    ! !! 8LMWTVSKVEQHVE[WEGLIGOIVFSEVH!! !!

    MQTSVXEGQKVETLMGW!MQTSVXEGQTVSKVEQ!!

    !! 8LMWGPEWWHVE[WEGLIGOIVFSEVHSRXLIKVETLMGW[MRHS[!! 8LIWM^ISJXLIGLIGOIVFSEVHMWWTIGMJMIHF]XLI!! GSRWXERXW263;7ERH2'309127ERHXLIGLIGOFSEVHJMPPW!! XLIZIVXMGEPWTEGIEZEMPEFPI!! !!

    TYFPMGGPEWW'LIGOIVFSEVHI\XIRHW+VETLMGW4VSKVEQ_!!

    ! 2YQFIVSJVS[W!! TVMZEXIWXEXMGJMREPMRX263;7!!!

    ! 2YQFIVSJGSPYQRW!! TVMZEXIWXEXMGJMREPMRX2'309127!!!

    ! 6YRWXLITVSKVEQ!! TYFPMGZSMHVYR_!! MRXWU7M^I!KIX,IMKLX263;7!! JSVMRXM!M263;7M_!! JSVMRXN!N2'309127N_!!

    MRX\!NWU7M^I!

    ! MRX]!MWU7M^I!! +6IGXWU!RI[+6IGX\]WU7M^IWU7M^I!! WUWIX*MPPIHMN!!! EHHWU!! a!! a!! a!a!!

    !

    !

    !

    http://technicalsupportindia.blogspot.com/

    http://technicalsupportindia.blogspot.com/
  • 8/6/2019 Prog Patterns

    5/9

    Mehran Sahami Handout #12

    CS 106A October 5, 2007

    Assignment #2: Simple Java Programs

    Due: 3:15pm on Monday, October 15thBased on a handout by Eric Roberts

    Your job in this assignment is to write programs to solve each of these six problems.

    1. Write a GraphicsProgramsubclass that draws a pyramid consisting of bricks

    arranged in horizontal rows, so that the number of bricks in each row decreases by

    one as you move up the pyramid, as shown in the following sample run:

    The pyramid should be centered at the bottom of the window and should use

    constants for the following parameters:

    BRICK_WIDTH The width of each brick (30 pixels)

    BRICK_HEIGHT The height of each brick (12 pixels)

    BRICKS_IN_BASE The number of bricks in the base (14)

    The numbers in parentheses show the values for this diagram, but you must be ableto change those values in your program.

    http://technicalsupportindia.blogspot.com/

    http://technicalsupportindia.blogspot.com/
  • 8/6/2019 Prog Patterns

    6/9

    2

    2.

    archery target or, if you prefer commercial applications, a logo for a national

    department store chain that looks like this:

    This figure is simply three GOval objects, two red and one white, drawn in the correct

    order. The outer circle should have a radius of one inch (72 pixels), the white circle

    has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The

    figure should be centered in the window of a GraphicsProgramsubclass.

    3. Write a GraphicsProgramsubclass that draws a partial diagram of the acm.program

    class hierarchy, as follows:

    The only classes you need to create this picture are GRect, GLabel, and GLine. The

    major part of the problem is specifying the coordinates so that the different elements

    http://technicalsupportindia.blogspot.com/

    http://technicalsupportindia.blogspot.com/
  • 8/6/2019 Prog Patterns

    7/9

    3

    of the picture are aligned properly. The aspects of the alignment for which you are

    responsible are:

    The ZLGWK and KHLJKW of the class boxes should be specified as named constants

    so that they are easy to change.

    The labels should be centered in their boxes. You can find the width of a label by

    calling label.getWidth() and the height it extends above the baseline by calling

    label.getAscent(). If you want to center a label, you need to shift its origin by

    half of these distances in each direction.

    The connecting lines should start and end at the center of the appropriate edge of

    the box.

    The entire figure should be centered in the window.

    4. In high-school geometry, you learned the Pythagorean theorem for the relationship ofthe lengths of the three sides of a right triangle:

    D2 + E2 = F2

    which can alternatively be written as:

    F = ba22

    Most of this expression contains simple operators covered in Chapter 3. The one

    functionMath.sqrt. For example, the statement

    double y = Math.sqrt(x);sets y to the square root ofx.

    Write a ConsoleProgramthat accepts values fora andb as ints and then calculates

    the solution of c as a double. Your program should be able to duplicate the

    following sample run:

    http://technicalsupportindia.blogspot.com/

  • 8/6/2019 Prog Patterns

    8/9

    4

    5. Write a ConsoleProgramthat reads in a list of integers, one per line, until a sentinel

    value of 0 (which you should be able to change easily to some other value). When the

    sentinel is read, your program should display the smallest and largest values in the

    list, as illustrated in this sample run:

    Your program should handle the following special cases:

    If the user enters only one value before the sentinel, the program should report

    that value as both the largest and smallest.

    If the user enters the sentinel on the very first input line, then no values have been

    entered, and your program should display a message to that effect.

    6. -prize-winning book *|GHO (VFKHU %DFK contains

    many interesting mathematical puzzles, many of which can be expressed in the form

    of computer programs. In Chapter XII, Hofstadter mentions a wonderful problem that

    is well within the scope of the control statements from Chapter 4. The problem can

    be expressed as follows:

    Pick some positive integer and call it Q.

    IfQ is even, divide it by two.

    IfQ is odd, multiply it by three and add one.

    Continue this process until Q is equal to one.

    On page 401 of the Vintage edition, Hofstadter illustrates this process with the

    following example, starting with the number 15:

    15 is odd, so I make 3Q+1: 4646 is even, so I take half: 2323 is odd, so I make 3Q+1: 7070 is even, so I take half: 3535 is odd, so I make 3Q+1: 106

    106 is even, so I take half: 5353 is odd, so I make 3Q+1: 160

    http://technicalsupportindia.blogspot.com/

    http://technicalsupportindia.blogspot.com/
  • 8/6/2019 Prog Patterns

    9/9

    5

    160 is even, so I take half: 8080 is even, so I take half: 4040 is even, so I take half: 2020 is even, so I take half: 1010 is even, so I take half: 5

    5 is odd, so I make 3Q+1: 1616 is even, so I take half: 88 is even, so I take half: 44 is even, so I take half: 22 is even, so I take half: 1

    As you can see from this example, the numbers go up and down, but eventually at

    least for all numbers that have ever been tried comes down to end in 1. In some

    respects, this process is reminiscent of the formation of hailstones, which get carried

    upward by the winds over and over again before they finally descend to the ground.

    Because of this analogy, this sequence of numbers is usually called the +DLOVWRQHVHTXHQFH although it goes by many other names as well.

    Write a ConsoleProgramthat reads in a number from the user and then displays the

    showing the number of steps taken to reach 1. For example, your program should be

    able to produce a sample run that looks like this:

    The fascinating thing about this problem is that no one has yet been able to prove that

    it always stops. The number of steps in the process can certainly get very large. How

    many steps, for example, does your program take when Q is 27?

    http://technicalsupportindia.blogspot.com/