New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Computer Science I

by: Reuben Rohan

Computer Science I CMPU 101

Reuben Rohan

GPA 3.88

Jennifer Walter

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Jennifer Walter
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 61 page Class Notes was uploaded by Reuben Rohan on Wednesday October 28, 2015. The Class Notes belongs to CMPU 101 at Vassar College taught by Jennifer Walter in Fall. Since its upload, it has received 48 views. For similar materials see /class/230534/cmpu-101-vassar-college in ComputerScienence at Vassar College.

Similar to CMPU 101 at

Popular in ComputerScienence


Reviews for Computer Science I


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/28/15
CHAPTER 7 lots and Memory CMPUlOl Computer Science I ProblemSolving and Abstraction Fall 2008 Jennifer Walter adapted from slides by Eric Roberts Binary Notation Bytes and words can be used to represent integers of different sizes by interpreting the hits as a number in binary notation Binary notation is similar to decimal notation but uses a different base Decimal numbers use 10 as their base which to its right Bin notation uses base whic means that each position counm for twice as much as follows elmemma Octal and Hexadecimal Notation Because binary notation tends to get rather long computer scientists often prefer octa ase 8 or hexadecimal ase 6 notation instead Octal notation uses eight digim 0 to 7 39 tation uses sixteen igits 0 to 9 followed by the letters A through F to indicate the values 10 to 15 The following diagrams show how the number fortytwo appears in both octal and hexadecimal notation Octal hammerma 2 2xl2 10x110 5x840 2x1632 The advantage of using either octal or hexadecimal notation is at doing so makes it easy to translate the num er ac to individual bits because you can convert each digit separately Num bytes The unit th The calculation at the clear that the bin The number 42 is whatyou get ifyou count i The Structure of Memory The fundamental unit ofmemory inside a computer is called a bit which is a contraction of the words inary digit A it can be in ei er oftwo states usually denote as 0 and 1 The hardware structure of a computer comb39nes individual bits into larger unis modern architectures the smallest unit on which the hardware operates is a sequence of eight consecutive bits called a byte The following diagram shows a byte containing a combination 0 0s and 1s IIIIIIII 1 EEE ers are stored in still larger units that consist of multiple 39 at represents the most common inte er size on a particu ar hardware is called a word Because machines have different architectures the number of bytes in a word ay vary from machine to machine Numbers and Bases end of the preceding slide makes it ary representation 00101010 is equivalent to the number 42 When it is important to distinguish the base the text uses a small subscript like this 001010102 421U Although it is useful to be able to convert a number from one base to another it is important to remem er that the number remains the same What changes is how you write it down 39 w many stars are in the pattern at the right The number is the same whetheryou write it n English asforty two in decimal as 42 or nbinary as 00101010 t 39 i 39 2 i i Numbers do not have bases representations do Exercises Number Bases What is the decimal value for each ofthe following numbers 100012 1778 A015 65 As part of a code to identify the file type every Java class file begins with the following sixteen bits l l lolol lol lol l l l l lol How would you express that number in hexadecimal notation l l l l lol 1 010111011011 Memory and Addresses Every byte inside the primary memory of a machine is identi ed by a numeric address The addresses begin at 0 and extend up to the number of bytes in the machine as shown in the diagram on the right In these slides as well as in the diagrams in the text memory addresses appear as fourdigit hexadecimal numbers which makes addresses easy to recognize In Java it is impossible to determine the address of an object Memory addresses used in the examples are therefore chosen completely arbitrarily Memory diagrams that show individual bytes are not as useful as those that are organized into words The revised diagram on the right now includes four bytes in each of the memory cells which means that the address numbers increase by four each time HeapStack Diagrams It is easier to understand how Java works if you have a good mental model of its use of memory The text illustrates this B O a 9 s E 5 on 5 m a quotT M PP a a w a a N 391 g E B o r I r O E 539quot o r o 5 13 O 5 a the left and the stack on the right separated by a dotted line Whenever your program creates a new object a block of memory is added to the heap That block must be large enough to store the instance variables for the object along with some extra overhead space required for any object Overhead space is indicated in heapstack diagrams as a crosshatched box Whenever your program calls a method a block of memory is added to the stack The local variables for the method are each given space on the stack with some overhead information identifying the method When a method returns Java reclaims the memory in its frame A Complete HeapStack Trace public void run Rational a new Rational1 2 Rational b new Rational1 3 Rational c new Rational1 6 Rational sum aaddb addc printlnaquotquotbquotquotcquotquotsum Mk 39 8 8 6 Teananonal The Allocation of Memory to Variables When you declare a variable in a program Java allocates space for that variable from one of several memory regions One region of memory is reserved for variables that 7 are never created or destroyed as the program runs such as named constants and other class variables This information is called static data Whenever you create a new object Java allocates space from a pool of memory called the heap Each time you call a method Java allocates a new block of memory called a stack frame to hold its local variables These stack frames come from a region of memory called the stack In classical architectures the stack and heap grow toward each other to maximize the available space Object References Internally Java identi es an object by its address in memory That address is called a reference As an example when Java evaluates the following line Rational r1 new Rational1 2 it allocates heap space for the new Rational object For this example imagine that the object is created at address 1000 The local variable r1 is allocated in the current stack frame and is assigned the value 1000 which identifies the object stack The next slide traces the execution of the TestRational program from Chapter 6 using the heapstack model The Pointer Model The heapstack diagram at the lower left shows the state of memory at the end of the last slide The diagram at the lower right shows exactly the same state using arrows instead of numeric addresses This style of diagram is said to use the pointer model stack stack sum Addresses vs Pointers Garbage Collection I The two heapstack diagram formawithe address model and I One fact that the pointer model makes clear in this diagram is the pointer modelgdescribe exactly the same memory state that there are no longer any references to the Rational value The models however emphasize different things 56 That value has now become garbage The ointer model em hasizes the re1ationshi between the refxrrce 39 From time to me Java ms throngh the heap and redaims and 6 object and makpes the diagmm easierwpfonow anygarbage This process is called garbage collection stack heap stack heap stack Primitive Types vs Objects StackHeap Diagrams I At rst glance Java s rules for passing objects as argumenw Suppose we run the following code starting with the method seem to differ from the rules Java uses with arguments that caller are primitive types I When you pass an argument of a primitive type to a method Pri j ztexvfd auer Java copies the value of the argument into the parameter thi ncrenentor variable As aresult changes to the parameter variable have thisPrintlmquotx Z quotx no effect on the argument I private void increment nt y When you pass an object as an argument any changes that wt you make to the instance variables inside an obj ectiusually thls39Pnntln w N V by calling settersihave a permanent effect on the object I Stackheap diagrams make the reason for this seeming Only primitive local variables are created in these methods so no heap space asymmetry c ear When you pass an object to amethod Java is needed Note that when the increment method returns no change has been copies the reference the memory address but not the object made to the argument x With primitive types only the value of the argument iwelf is copied StackHeap Diagrams Suppose that the class Number And suppose we execute the is de ned a follow 39 following i t public class Number private int value StackHeap diagram smelt alone program public Nulnberint n private void callero thisvalue n Number x new Numberu39l peas this addlx de Fm thisprintnquotx quotx x a public int getValueo we return thisvalue private void addlmunber y ysetValuewqet lalue0d private void callero public void setValueint n thisprintnquoty quot y Number x new Number17 thisvalue n thisaddlx thisprintlnquotx quotx public string tostringo return quotquotthisvalue private void addlmumber y t Output y setValuey getValue 1 y 18 thisprintlnquoty w y x18 StackHeap diagram hump mick mu m E m xwe PPR x is instantiated in this example the address on the en When heap where the Number object named x is stored is wrltt on the stack and named x in the stack fmme for the caller method I When addl is called the address in the stack for x is copied s e argument and e parameter name refer to the same object on the heap Using Wrapper Classes You can create an instance of a wrapper class by calling its constructor with the primitive value For example the line Integer five new Integer5 creates anew Integer object containing the value 5 heap Stack 33 mm I The value stored in the variable five is an obj ect and you can use it in any contexw that require objects I For each of the wrapper classes Java de nes a method to retrieve the primitive value as illustrated below int underlyingValue fiveintVa1ue Exercise StackHeap Diagrams Suppose that the classes Point and Line are de ned as follows public class Poin t public class Line Pointint x int y P ublic LinePoint pl public ex 1 Polnt p2 cy y start pl finish p2 he methods appear here other meLhads appear hm private int cx ivate int Cy private Point start private Point finish Draw a heapstack diagram showing the state of memory just before the following constructor nishes public TestLinePointO Point 1 ed Po Wrapper Classes I The designers of Java chose to separate the primitive types om the standard class hierarchy mostly for ef ciency Primitive values take less space and allow Java to use more of the capabilities provided by the hardware I Even so there are times in which the fact that primitive types are not objects gets in the way There are many tools in the Java ariesisever of which you will encounter later in the bookithat work only with objects I To get aron this problem Java includes awrapper class to correspond to each of the primitive types I U boolean lt gt Boolean float 1 Float byte lt gt Byte int lt gt Integer char 4 Character long lt gt Long double 4 Doub e short 4 Short Boxing and Unboxing I As of Java Standard Edition 50 Java automatically converts alues back an e een ri itive type an th corresponding wrapper class For example if you write Integer five 5 Java will automatically call the Integer constructor I Similarly if you then write int six five 1 Java will automatically call intValue before the addition I These opemtions are called boxing and unboxing I Although boxing and unboxing can be quite convenient this feature can generate confusion and should be used with care Solution StackHeap Diagrams Address Model Pointer Model hump stack hump stack um cx um cx a El E 1 U Um cx m a a cx mu By a o me n me 1 2m me n n2 3 mm W aquot in um Linking Objects Together I Although most examples of this technique are beyond the scope of a rst course references are particularly important in computer science because they make it possible to represen t the relationship among objects by linking them together in various Ways One common example is called a linked list in which each object in a sequence contains a reference to the one that follows it data data data data link hnk link link Java marks the end of linked list using the constant null which signi es a reference that does not actually point to an ect The value null has several other uses as you Will discover in the chapters that follow Message Passing in Linked Stmctures To represent this messagepassing mllie class sirmum irn e you might use a definition 1 canstansts a n err signal t n such as the one shown on the right mllie sieuarwmxtstme name Slynal39l nwex iankt You can then initialize a chain of tumvan new Signal39l owe objects like this quot quotquotquot 1 1 Signal this tunes and passes the 1 message along tn the next one public naau sannaitt t n aht Cull entrarrex H a tnextr nniit t nexl39l39nwex saanaitt link this twat as lit 39l public naau ianhtcnnentrarreatt t code to draw a wz on rm tower l narrate instance vaaaaaies narrate staana tamuane Calling signal on the first tower rxivau sirimam nexumx sends amessage down the chain The Beacons of Gondor For eruwer Gandalfcned aloud to his horse 1m Shadowfax e man in and ame an Eilenach and t ere 2y g0 Speeding westNardal Erelas Merxmma Celenhed and me Hdr rien an the borders afRahtm 71 R R Tolkien The Return ofthe King 1955 In a scene that Was brilliantly captured in Peter Jackson s lm adaptation of The Relum of the King Rohan is alerted to the danger to Gondor by a succession of signal res moving from moun ain top to mountain top 395 scene is a perfect illustration ofthe idea ofmessage passing in a linked list ggt t Enhs Whitman The End CHAPTER 4 ament F arms are mmw s mascarash em 1mm le anaemia use CMPU l 01 Computer Science I ProblemSolving and Abstraction Jennifer Walter adapted from slides by Eric Roberts Control Statements and Problem Solving Before looking at the individual control statement forms detail it helps to look more holistically programs that make use ofcommon control p in at a couple of attems The next few slides extend the AddZIntegers program from Chapter 2 to create programs that add longer lists of integers These slides illustrate three different strategies redetermlned number of times 7 Repeating the input cycle until the user enters a special sentinel value The RepeatN Tlmes ld1om One strategy for generalizing the addition program is to use the RepeatN Times idiom which executes a set of statements a specified number of times The general form ofthe idiom 39 for int i o i lt repetitions 1H statements to be repeated information about the number of repetitions is speci ed by the rst line in the panem which is called the heade line The statements to be repeated are called the body of the for statement and are indented with respect to the header line A control statement that repeam a section of code is called a loop Each execution ofthe body ofa loop is called a cycle Statement Types in Java Programs in Java consist of a set of classes Those classes contain methods and each of those methods consists of a sequence of statements Statements in Java fall into three basic types Simple statements are formed by adding a semicolon to the end ofa Java expression Compound statements also called blocks consist of a sequence of statements enclosed in curly braces Control statements fall into two categori s 7 Conditional statemenu that specify some kind oftest r Iterative stamments that specify repetition The Add4Integers Program If you don t have access to control statements the only way you can increase the number of input values is to add a new statement for each one as in the following example public class Mddlnleqexs extends Cnnsnlerngxam I a lnmnas Plug xam adds fulll numhexs b t nl e leadInN Enlex n ant n2 ant n3 an tut t e n palntlnmne tatal is i tatal i D This strategy however is dif cult to generalize and would clearly be cumbersome Lfyou needed to add 100 values The AddN Integers Program This program uses the RepeatN Times idiom sum of a predetermined number of integer va the named constant II to compute the lues speci ed by puhlic class nddlllnleqexs extends Cnnsnlernqxam uhlic void xiiin 39n lntwnas Plnqxam adds it II numhexs b n ant tatal e f1inl1 ilt il ant value xeaulnm a t t tal K value plantlnmne tatal is i tatal H pxivale static final int II inn The RepeatUntilSentinel Idiom A better approach for the addition program that works for any number of values is to use the RepeatUntilSentinel idiom which executes a set of statements until the user enters a speci c value called a sentinel to signal the end of the list while true prompt user and read in a value if value sentinel break rest ofloop body You should choose a sentinel value that is not likely to occur in the input data It also makes sense to de ne the sentinel as a named constant to make the sentinel value easy to change The AddI ntegerLi s t Program public void run printlnquotThis program adds a list of integersquot printlnquotEnter values one per ine using quot SENTIN39EL printlnquotto signal the end of the listquot int total while true int value readIntquot quot if value SENTIN39EL break total value printlnquotThe total is quot total quotquot Value t tal 6 8 8 Auulmegemm This program adds a list of integers Enter values one per line using 0 to signal the end of the list 1 2 3 90 The total is 6 slap man The AverageLi s t Program public class AverageList extends ConsoleProgram ic void run printlnquotThis program averages a list of numbersquot printlnquotEnter values one per line using quot SENTINEL printlnquotto signal the end of the listquot int total 0 int count 0 while true int value readIntquot 7 quot39 if value SEN NEL break total value count double average double total count39 printlnquotThe average is quot average quotquot private static final int SENTINEL 1 The AddI ntegerLi s t Program This program uses the RepeatUntilSentinel idiom to add a list of integers stopping when the user enters a value that matches the named constant SENT INEL public class AddIntegerList extends ConsoleProgram public void run printlnquotThis program adds a list of integersquot printlnquotEnter values one per line using quot SENTINEL printlnquotto signal the end of the listquot int total 0 while true int value readIntquot quot if value SENTIN EL break total value printlnquotThe total is quot total quotquot private static final int SENTINEL 0 Exercise Control Patterns Using the AddIntegerList program as a model write a new AverageList program that reads a set of integers from the user and displays their average Because 0 values might well appear for example in an average of exam scores change the sentinel value so that the input stops when the user enters 1 It is important to keep in mind that the average of a set of integers is not necessarily an integer The AverageList program will require the following changes 7 Convert the variable total to a double before computing the average 7 Change the definition of the SENT INEL constant 7 Keep a count of the number of input values along with the sum 7 Update the user messages and program documentation The if Statement The simplest of the control statements is the if statement which occurs in two forms You use the first form whenever you need to perform an operation only if a particular condition is true if condition statements to be executed if the condition is true You use the second form whenever you want to choose between two alternative paths one for cases in which a condition is true and a second for cases in which that condition is false if condition statements to be executed if the condition is true else statements to be executed if the condition is false Choosing between if and ifelse Choosing between if and ifelse I As is true with most progmmming construcw there is no hardandfast rule that will tell you Whether you need the public void run basic statement or the ifelse fernL printnquotThis program averages a list of numbers quot 39 printlnquotEnter values one per ine using v SENTINEL I The best general guideline is to think about the English erintlm39 Signal the em f the listquotW description of the problem you are trying to solve If that 339 description contains the Words else or otherwise there is a while true good chance that the solution will use the else keyword int value readmtv39 9 L if val e ENTINEL break As an example suppose that you Wanted to change the if value AverageList program so that it didn t include any zero 22 ame values in the average Here you need a simple if statement that makes sure that the score is not equal to 0 double average double total coun 39 I If you also Wanted to count the nonzero scores you would println The nonzero average is quot average quot need to add an else clause to increment a counter variable in the case that value was equal to 0 Common Forms of the if Statement The Operator The examples in the book use the if statement in the following I In addition to the if statement Java provides a more compact forms I Way to express conditional execution that can be extremely use ll in certain situations This feature is called the Single line if statement Multiline if statement with curly braces 0 erator pronounced quatiommarkfolon and is Pm of the P if condition expression structure The operator has the folloWlng form statement m0remtementS ccndztzcn espressmn espresszcn2 ifelse statement with curly braces Cascading if statement 39 Wheh JeVe eVelheteS the Operator 1t ISt dete hmes the E d t E d t value of condition which must be a boolean If condition is 1 can 10quot t 1 can an true Java evaluates expression and uses at as the value if statementsm statements It f l J 31 t t d else else if condition con 1 ion is a se ava ev ua es expression2 ins ea statemwmhti statementsz I You could use the operator to assign the larger of x and y mare elsdif conditions to the variable max like this 1 else statementsd max x gt Y x Y The sw1 tch Statement Example of the sw1 tch Statement The switch statement provides a convenient syntax for choosing The 5W1 tCh Statemth 5 useful Wheh the Program tht Cheese among a set ofpossible Paths among several cases as in the folloWlng example public void run switch EXPYESSZUVL printnThis program shows the of in a month v case V int month readIntquotEnter numeric month Jan1 quot statements to be executed zfespnesstcn v itch went break println 23 days 29 in leap yearsquot ase v2 break statements to be executed zfespnessmn v2 case 4 case 5 case 9 case 12 brea printlnquot30 daysquot r break 39 39 39 more case Clauses lfnggdgd39 39 39 case 1 case 3 case 5 case 7 case H Case 11 default printlnquot31 daysquot statements to be executed zfnu values match break break default 39 printlnquotIllegal month numberquot break The while Statement The while statement is the simplest of Java s iterative control statements and has the following form while condition statements to be repeated When Java encounters a while statement it begins by evaluating the condition in parentheses which must have a boolean value If the value of condition is true Java executes the statements in the body of the loop At the end of each cycle Java reevaluates condition to see whether its value has changed If condition evaluates to false Java exits from the loop and continues with the statement following the closing brace at the end of the while body The LoopandaHalf Pattern The while statement in Java always tests the condition at the beginning of each cycle of the loop Sometimes however you need to perform some computation before you can make the test In those situations the loopandahalf pattern is very useful while true computation necessary to make the test if testfor completion break computationfor the rest ofthe loop cycle Because the condition in the while statement itself is always true this loop would continue forever without some other strategy to indicate completion The loopanda half pattern uses the if and break statements to exit the loop When the test for completion becomes true Java executes the break statement which causes the loop to exit skipping the rest of the cycle The for Statement The for statement in Java is a particularly powerful tool for specifying the control structure of a loop independently from the operations the loop body performs The syntax looks like this for init test step statements to be repeated Java evaluates a for statement by executing the following steps Evaluate init which typically declares a control variable Evaluate test and exit from the loop if the value is false Execute the statements in the body of the loop Evaluate step which usually updates the control variable Return to step 2 to begin the next loop cycle SIM 9 The Digi tSum Program public void run printlnquotThis program sums the digits in an integerquot int n readIntquotEnter a positive integer quot 39 int dsum 0 while 11 gt 0 um n 95 10 n 10 printlnquotThe sum of the digits is quot dsum n dsum E 63E Dugnsum This program sums the digits in an integer Enter a positive integer 1729 The sum of the digits is 19 slap simulation RepeatUntilSentinel Revisited The repeatuntilsentinel pattern presented at the beginning of the chapter is an example of the loopanda half pattern while true prompt user and read in a value if value sentinel break rest ofloop body Although it might at rst seem as if this pattern is more complex than the more basic form of the while statement it turns out to be considerably easier for most students to use Several studies have demonstrated that students who use the loopanda half pattern are far more likely to write correct code than those who don t Comparing for and while The for statement for init test step statements to be repeated is functionally equivalent to the following code using while init while test statements to be repeated step The advantage of the for statement is that everything you need to know to understand how many times the loop will run is explicitly included in the header line Exercise Reading for Statements Describe the effect of each of the following for statements 1 for int i 1 i lt 10 i This statement executes the loop body ten times with the control variable i taking on each successive value between I and 10 2 for int i 0 i lt N i This statement executes the loop body N times with i countingfrom 0 to N 1 This version is the standardRepeat N Times idiom 3 forintn99ngt1n 2 This statement counts backward from 99 to I by twos 4 for int x 1 x lt 1024 x 2 This statement executes the loop body with the variable x taking on successive powers oftwofrom I up to 1024 Nested for Statements The body of a control statement can contain other statements Such statements are said to be nested Many applications require nested for statements The next slide for example shows a program to display a standard checkerboard in which the number of rows and number of columns are given by the constants NROWS and NCOLUMNS The for loops in the Checkerboard program look like this for int i 0 i lt NROWS i for int j 0 j lt NCOIUMNS j Display the square at row i and column j Because the entire inner loop runs for each cycle of the outer loop the program displays NROWSXNCOLUMNS squares Exercise Triangle Number Table Write a program that duplicates the sample run shown at the bottom on this slide which displays the sum of the rst N integers for each value of N from 1 to 10 As the output suggests these numbers can be arranged to form a triangle and are therefore called triangle numbers 8 8 8 Tuanglerahle 1234567836 12345678945 1234567891055 The Countdown Program public void run forintt10tgt0t printlnt y39 println quotLiftoff quot 39 t 839 Countdown 10 9 8 7 6 5 4 3 2 1 0 Liftoff slap Simulation The Checkerboard Program public void run double sqSize double getHeight NROWS for int i 0 i lt NROWS 39 for int j 0 j lt NCOLUMNS j double x j sqSize double y i sqSize eat 11 w GRectx y sqSize sqSize sqsetFilledi j 95 2 0 addsq sqSize i j x y sq gt E 6 6 8 checkerboau slap Simulation Design Issues Triangle Number Table As you think about the design of the TriangleTable program it will help to keep the following thoughts in mind The program involves two nested loops The outer loop runs through each of the values of N from 1 to the maximum the inner loop prints a series of values on each output line The individual elements of each output line are easier to display if you call print instead of println The print method is similar to println but doesn t return the cursor position to the beginning of the next line in the way that println does Using print therefore makes it possible to string several output values together on the same line The rz h output line contains n values before the equal sign but only n7 1 plus signs Your program therefore cannot print a plus sign on each cycle of the inner loop but must instead skip one cycle The TriangleTable Program public class TriangleTable extends ConsoleProgram public void run for int n l n lt MAXVALUE n int total 0 for int i l i lt n i if i gt 1 printquot quot printi total i printlnquot quot total Private constants private static final int MAXVALUE 10 The AnimatedSquare Program public void run GRect square new GRect0 0 SQUARESIZE SQUARESIZE square setFilled true square setFillColor ColorRED addsquare double ix getWidth SQUARESIZE NSTEPS double dy getHeight SQUARESIZE NSTEPS for int i 0 i lt NSTEPS i squ removedx dy pause PAUSETIME square 1 dx dy E 7353TTTTTATTTEEEQEEETTTAAAAAAAA smnmmmw Simple Graphical Animation The while and for statements make it possible to implement simple graphical animation The basic strategy is to create a set of graphical objects and then execute the following loop for int i 0 i lt NS39139EPS i update the graphical objects by a small amount pausePAUSE391 IME On each cycle of the loop this pattern updates each animated object by moving it slightly or changing some other property of the object such as its color Each cycle is called a time step After each time step the animation pattern calls pause which delays the program for some number of milliseconds expressed here as the constant PAUSETIME Without the call to pause the program would nish faster than the human eye can follow The End c n A r r e n 1 n 1tdriven Programs rnamwnaandmsnaraamvm tar n mind mkdm mwm ks m CMPUlOl Computer Science I ProblemSolving and Abstraction Jennifer Walter adapted from shdes by Eric Roberts Event Types Java events come in many different types The event types used in this book include the following 7 Mouse evens which occur when the user moves or clicks the mouse 7 Keyboard events whrch occur when the user types on the keyboard 7 Action events which occur in response to usemnterface actions Each event type is associated with a set of methods that specify how listeners should respond These methods are de ned in a listener interface for each event type As an example one of the methods in the mouse listener interface is mousecl icked As you would expect Java calls that method when you click the mouse Listener methods like mouseclicked take a parameter that contains more information about the event In the case of useclicked e argumen is a MouseEvent indicating the location at which the click occurred Respondmg to Mouse Events programs respond to mouse events by following these general steps 1 De ne a run or init method that calls this addMouseListeners 0 2 Write new de nitions of any listener methods you need The most common mouse events are shown in the following table along with the name of the appropriate listener method l l l l l ouseReleasedE Called when the mouse button is released adv e dw the ouse cane Called when the mouse is dragged with the button down The parameter 2 is a MouseEvent object which provides more data about the event such as the location ofthe mouse The Java Event Model Graphical applications often make it possible for the user to control the action of a program by usin an input device such as a mouse rograms that support user control are called interactive programs User actions such as clicking the mouse are called events Programs that respond to events are said to be eventrdriven n eventdriven programs user input may not occur at 39 es A running program may not tell the user when to click the mouse The user decides when to click the mouse and the program responds ecause events are not controlled by the program they are said to be asynchronous you write an eventdriven program you indicate the events to which you wish to respond by designating an object as a listener for a even en e even occurs message is sent to the listener triggering a response EventDriven Program innnxt acmpxngxamquot mpnxl acmqxayhlcsquot impult javaawlevenlquot In Dxaws a cixcle anywhexe tne nsex clicks the nanse a mldie class Dxawsplamap extends Glaphicsl anxam public static final int unmisle 2n nnniie void inittt thisaddnnuseListenels H mlAlia vnid nnnseciiekedlunnseavent et cowl irl new covnlouucisxznxucisxzz e ii eie lt illdtru s enis idd e ii eie e geexo e geey 0 s mldie statie vniul nain lstxineu alqu new Dxamsplamar staxtn A Simple LineDrawing Program In all likelihood you have at some point used an application that allows you to draw lines with the mouse In Java that program takes less than a page of co e public class DxawLines extends Glayhicsl xngxam Initializes tne ylnqxam hy enabling the mouse 1istenexs nnniie void initlt tnisaddnnnsetistenexs u called on mouse pies tn exeate a ne nnniie void nonseexessedmnnsenvent t e line new GLineteqetxH edetiut eqele edetym thisadduinet quot can ed on mouse dzaq to extend the endpoint a mldie vniul mnuseraqqedtMnuseEvenl et 1inesetandenintledetxtt edetym quot Pxivate instance vaxiahles 39l xxivau Gum line mam method and lmpo Dragging Ob ects on the Canvas The Dragobj ects program on the next slide uses mouse events to drag objects around the canvas 7 Pressing the mouse button selects an object 7 Dragging the mouse moves the selected object 7 Repeating these steps makes it possible to drag other objects 7 Clicking the mouse moves the selected object to the front a e e Draaohleds The DragObjects Program The DragObjects Program import acmgraphics import acmprogram import java awt event This class displays a mouse draggable rectangle and oval public class DragObjects extends GraphicsProgram Initializes the program p 39c void init GRect rect new GRect100 100 150 100 rect setFilledtrue rect setColor ColorRED this add rect GOval oval new GOval300 115 100 70 oval setFilledtrue oval setColor Color GREEN this add oval this addMouseListeners main method not shown Called on mouse press to record the coordinates of the click public void mousePressedMouseEvent e thislast new GPointegetPoint 0 thisgobj getElementAtthislast Called on mouse drag to reposition the object pub 39c void mouseDraggedMouseEvent e if thisgobj null this gobj move egetX this lastgetX egetY this lastgetY thislast new GPoint egetPoint a e on mouse c ic o move is o jec o e ron Clld l39kt th39 b39ttthf t public void mouseClickedMouseEvent e if thisgobj null thisgobjsendToFront Private instance variables private GObject gobj private GPoint last The object being dragged The last mouse position page Z 02 slap coda Identifying the Key The process of determining which key generated the event depends on the type of key event you are using If you are coding the keyTyped method the usual strategy is to call getKeyChar on the event which returns the character generated by that key The getKeyChar method takes account of modi er keys so that typing the a key with the SHIFT key down generates the character 39A39 page 1 of slap coda Responding to Keyboard Events The general strategy for responding to keyboard events is similar to that for mouse events even though the events are different Once again you need to take the following steps 1 Call addKeyListeners from the constructor 2 Write new definitions of any listener methods you need The most common key events are keyPressede l Called when the user presses a key l keyReleased e l Called when the key comes back up i keyTyped e Called when the user types presses and releases a key In these methods 2 is a KeyEvent object which indicates which key is involved along with additional data to record which modifier keys SHIFT CTRL and ALT were down at the time of the event Creating a Simple GUI In addition to mouse and keyboard events application programs may include a graphical user interface or GUI pronounced gooey consisting of buttons and other onscreen controls Collectively these controls are called interactors Java de nes many types of interactors most of which are part of a collection called the Swing library described in section 106 You create a GUI by constructing the Swing interactors you need and then arranging them appropriately in the program window The text outlines two strategies for arranging interactors on the screen The simple approach is to use a control strip along one of the edges of the window as described on the next slide You can however create other GUI layouts by using Java s layout managers as described in section 107 Using the Control Strip When you create an instance of any Program subclass Java divides the window area into ve regions as follows NORTH CENTER HmmE Hmgtm SOUTH The CENTER region is typically where the action takes place A ConsoleProgram adds a console to the CENTER region and a GraphicsProgram puts a GCanvas there The other regions are visible only if you add an interactor to them The examples in the text use the SOUTH region as a control strip containing a set of interactors which are laid out from left to right in the order in which they were added The HitchhikerButton Program import acmprogram import java awt event import javax swing This program puts up a button on the screen which triggers a message inspired by Douglas Adams39s novel public class HitchhikerButton extends ConsoleProgram Initializes the user interface buttons public Void init this addnew J39ButtonquotRedquot SOUTH this addActionListeners Responds to a button action public void actionPerformedActionEvent e if egetActionCommand equals quotRedquot printlnquotPlease do not press this button againquot main method not shown Detecting Action Events Before you can detect action events you need to enable an action listener for the buttons on the screen The easiest strategy is to call this addActionListeners at the end of the init method This call adds a listener to all the buttons on the display You specify the response to a button click by overriding the de nition of actionPerformed with a new version that implements the correct actions for each button This entails adding an actionPerformed method to your program that has the declaration line public void actionPerformed ActionEvent e Creating a GUI with a Single Button Arthur listened for a short while but being unable to understand the vast 39 39 rd was saying e egan to let his mind wander trailing his ngers along the edge ofan incomprehensible eomputerbank he reached out andpressed an invitingly large red button on a nearby panel The panel lit up with the words Please do notpress this button again iDouglas Adams Hitchhiker s Guide to the Galaxy 1979 The HitchhikerButton program on the next slide uses this vignette from Hitchhiker s Guide to the Galaxy to illustrate the process of creating a GUI without focusing on the details The code creates a single button and adds it to the SOUTH region It then waits for the user to click the button at which point the program responds by printing a simple message on the console 39 5 e 3 HlichhlkerEu on Please do not press this button again Please do not press this button again 1HedI The JButton Class The most common interactor in GUIbased applications is an onscreen button which is implemented in Swing by the class JButton A JButton object looks something like 1 Push Me I The constructor for the JButton class is new J39Button label where label is a string or graphic that appears inside the button The button shown earlier on this slide is created by J39Button pushMeButton new J39ButtonquotPush Mequot When you click on a button Java generates an action event which in turn invokes a call to actionPerformed in the ActionListeners you add to the program Detecting Action Events If there is more than one button in the application you need to be able to tell which one caused the event There are two strategies for doing so Call getSource on the event to obtain the name of the button itself in this case the JButton must be an instance variable N Call getActionCommand on the event to get the action command string which is initially set to the button label in this case the JButton can be local to the init or run method Adding Features to DrawSplatMap To illustrate the J Button Swing interactor we ll add a Jbutton to the DrawSplatMap application First we ll add a Clear button that erases the screen Adding the button is accomplished in the init method public void init thisadd new J39ButtonquotClearquot SOUTH this addActionListeners The response to the button appears in actionPerformed public void actionPerformedActionEvent e i egetActionCommand equals quotClearquot this removeAll Solution Interactive Stoplight Exercise Interactive Stoplight Using the Stoplight class you wrote for Lab 5 write a GraphicsProgram that creates a stoplight and three buttons labeled Red Yellow and Green as shown in the sample run below Clicking on a button should send a message to the stoplight to change its state accordingly 6 6 8 Gsiop Igmcul l Had I t Yellow 3 I Green l Solution Interactive Stoplight import acmprogran for Graph ic 5 Program import javaawtevent for ActionListener import javax swing for JButtons public class TestStopLight extends GraphicsProgranI public static final int APPLICATIONWIUI H 250 public static final int APPLICATIONHEIGHT 475 public static final int RED 1 public static final int YELLOW 2 public static final int GREEN 3 public static final int X 20 Y 20 3 JButton instance vars to be added along south control strip private JButton redgreenyellow instance variable the StopLight private StopLight stopLight main method not shown public void init th39 stopLight new stopLightxY7 thisstopLightaddthis7 thisred new JButtonquot Red II thisaddthisred SOUTH 7 39 green new JButtonquotGreen II H m thisaddthisyellow sown is addnctionListeners 7 th end run method public void actionPerformedActionEvent e if e tsource equalsthisred stopLight setLight RED 7 else if egetsourceequalsthisyellow stopLight setLight YELLOW else if egetsourceequalsthisgreen stopLight setLight GREEN 7 end actionPerformed method The J ToggleButton Class The JToggleButton class is another type of button that is similar to J39Button but maintains an onoff state On the screen a JToggleButton looks just like a J39Button except for the fact that it stays on after you release the mouse button As its name suggests a JToggleButton toggles back and forth between on and off when it is clicked Clicking the rst time turns it from off to on clicking a second time turns it off Toggle l k You can determine whether a JToggleButton is on by calling isSelected which returns true if the button is on The JToggleButton class itself is not used as much as two of its subclasses JCheckBox and J39RadioButton which are described on the next two slides The J CheckBox Class The JCheckBox class is a subclass of JToggleButton and therefore inherits its behavior In terms of its operation a JCheckBox works exactly like an instance of its parent class The only difference is in what the button looks like on the screen In a JCheckBox the button label appears to the right of a small square that either contains or does not contain a check mark like this M cheokBox k Because a JCheckBox is a JToggleButton you can call the isSelected method to determine its state Like a JButton a JCheckBox generates action events when it is clicked Both of these classes inherit this behavior from AbstractButton which is their common superclass The JRadioButton Class The J39RadioButton class also extends JToggleButton and behaves in much the same way In this case the button is displayed as a circle that is tinted and marked with a dot when it is selected as follows uhknadio button Radio buttons are ordinarily not used individually but instead as a set If you create a ButtonGroup object and then add several radio buttons to it the Swing libraries make sure that only one of those buttons is selected at a time Grouped radio buttons are used to allow the user to choose among several mutually exclusive options As an example the text extends the DrawstarMap program to allow the user to choose the size of the star by selecting a radio button kSmall Medium 4 Large The JLabel Class The interactors you display on the screen sometimes don t provide the user with enough information In such cases it is useful to include JLabel objects which appear as text strings in the user interface but do not respond to any events As an example if you wanted to label a slider so that it was clear 1t controlled s12e you could use the follow1ng code to produce the control strip shown at the bottom of the screen this add new J39Label quotSmallquot SOUTH 39 this addsizeSlider SOUT this addnew J39Label quotLargequot SOUTH 6 9 8 Draustarmap Small H Large The HelloGUI Program import acmprogram import javaawtevent import javaxswing This class displays a greeting whenever a name is entered public class HelloGUI extends ConsoleProgram public void init public void actionPerformedActionEvent e Private instance variables private JTextField nameField thisnameField new JTextFieldlO thisadd new J39LabelquotNamequot SOUTH this add nameField SOUTH nameField addActionListenerthis if egetSource this nameField this printlnquotHello quot thisnameFieldgetText this nameFieldsetText quotquot main method not shown The JSlider Class In many applications you want to let the user adjust a value over a wide range instead of selecting among a set of options The Swing libraries include several different interactors that allow the user to adjust a parameter The text uses the JSlider class which appears on the screen like this r itbgv The user can adjust a JSlider by dragging the slider knob The simplest form of the JSlider constructor looks like this new JSlider min max value where min and max are integers giving the minimum and max1mum values of the s11der and value 1s the 1n1t1al value You can retrieve the current value by calling getValue The JTextField Class There are some situations in which keyboard input is necessary in a GUI You can accept keyboard input in a user interface by using the JTextField class which provides the user with an area in which it is possible to enter a single line of text The HelloGUI program on the next slide illustrates the use of the JTextField class in a ConsoleProgram that prints a greeting each time a name is entered in the text eld a e e HelloGUI Hello world Hello Eric Name ENC Notes on the JTextField Class The constructor for the JTextField class has the form new J39I39extField columns where columns is the number of text columns assigned to the eld The space often appears larger than one might expect because Java reserves space for the widest characters You can get and set the string entered in a JTextField by calling the getText and setText methods A JTextField generates an action event if the user presses the ENTER key in the eld If you want your program to respond to that action event you need to register the program as an action listener for the eld In the HelloGUI example the action listener is enabled by the statement nameField addActionListener this Structural Recursion CMPUIOI ProblemSolving and Abstraction Jennifer Walter Vassar College Fall 2008 slides originally written by Marc Smith lnte rfaces Declaring a program called an interface is useful when you want to de ne the same instance methods in different classes and you want to refer to those different classes by the same typename Classes that implement the same interface are all members of the interface type The interface represents a union of classes with similar functionality Interface de nition line public interface InterfaceName Subclasses of interfaces use the following class de nition public class className implements lnterfaceName Containment Book u String title Contalns Author author quot contains Author contains String name int dob String instance char letters Sub and Superclasses You already know that you can write classes that extend existing classes In effect when a class extends an existing class the extending class has multiple types its own type and the type of its superclass For example any class you39ve written that extends ConsoleProgram is de ning a data type that is a subclass of the superclass ConsoleProgram and is of type ConsoleProgram as well Another type of superclass is called an interface lnte rfaces Interfaces de ne common behaviors methods for subclasses But they do not provide implementations for any ofthose methods The method de nitions in an interface have no curly braces ie no bodies they have only a method de nition line followed by a semicolon Any classes that have the quotimplementsquot keyword in the class de nition must provide implementations for each method de nition in the interface Why do we care about interfaces Because they allow us to write structural recursive programs and to use polymorphic references Selfcontainment Objects can contain instance variables of their own type A set of classes that implement the same interface is called a union of classes In Java classes can contain elds whose type is the same as any of the interfaces they implement Example Recursive de nition of a list A List is either 0 ie an ob39ect with no elds 0 empty a construction consisting of ie an object ith two elds We can translate this de nition into a class hierarchy the rst element the rest of the List Example Recursive de nition of a list e can translate this hierarchy into Java code public interface IList pulic class MTList implements Ilist public MTList lList union IList public class ConsList contains implements r l l l MTL st private IL ist rest public ConsListint first IList rest ConsList I I I thisfirst flrst thisrest rest To add a method to a union of classes I Add a quotblankquot method to the interface lList if the method is not de ned in the Object class Interfaces hold only method signatures with no braces or body code 2 Add a nonrecursive method to the MTList class that does what an empty list should do in each particular situation 5quot Add a recursive method to the ConsList class containing the statements to do what the method is supposed to do for a nonempty list Example Recursive de nition of a list A List is either empty class MTList the base case a construction class ConsList consisting of the rst element the rest of the List 39lnterfaces never contain constructors or instance variables because the cannot be instantiate lList union contains IList rest A view of object containment boxes in boxes List Creation statement new ConsList42 new ConsList43 new ConsList 44 new ConsList 45 n Resulting List Structure Compute the length of a list If we wish to compute the length of lists of type lList we must add a de nition line for a length method to interface lList Once we ve de ned length in the interface we must de ne the length method in all classes that implement lList MTList and ConsList Where to begin Let s start with the interface and work our way down c mpute the length f a quotSt List Class Hierarchy Union interface List public interface IList class ConsList public int length H length length of constructed list is l len th of Class MTList the rest of this list H public int length length of empty list is z ro return 1 thisrestlength first rest public int length return 0 recursive l h I I t t IL t what type of object IS eng 0 m 39 15 not recursive thisxestg lengtm base case Override toString so we can print Lists Let s create some lists and class MTList class ConsList see look H H Welcome to DrJava Working directory is usersDesktop string representation of t t t string representation of gt new MTList an empty is d l t k 5 Congtru te 15 0 Strin reresentation ofthe emt lis public string toString t Public String toStrlngO gt new consList42 new MTList return quot quot 42 0 return quotquot list containing one element also contains the empty IIs thisfirst quot quot not recursivequot thisresttostring gt IList t new MTList quotquot gt new coln sList42 mt Nobnankmethod added to List for recursive how t 5trin8 because the hint what is thisrest gt 1 I 2 I 3 1 method overridden is l l 0 list of 3 elements contains list of 2 elements which d f d Ob t I contains list of element which contains the empty list e me In jeC cass new consListl new consList2 new consList3 mt Questions about lists Now that we can build lists and print lists let s see what kinds of questions we can ask about lists What is the length ofthe list How many occurrences of some value are there Does the list contain a particular value How many even numbers are in the list Does the list contain all odd values Does list contain a particular value interface List Questions about interface IList dass ConSLiSt Public b00185 39 W What is the length ofthe list constructed llst elther has x as x flrst element or x may be 111 fe f 11 How many occurrences of some value are there class MTLIst m fmpty list contains no elements Does the list contain a particular value How many even numbers are in the list recurswe what t e of ob39ect is Y 1 Does the list contain all odd values not recursuve thISJ estg base case How many times does a value occur in list interface List interface IList dass ConSLiSt public int countxint x m k constructed llsl elther has x as x flrst element or x may be 1n rest k of llsl class MTLIst V x empty llsl contems no elements recursive not recursive base case c H A PT E R s h ads Witth 2ndth are unacmmyhsh aware immhwrhmlllu um CMPUlOl Computer Science I ProblemSolving and Abstraction Fall 2008 Jennifer Walter adapted from slldes by Erlc Roberts Method Calls are Expressions Method calls in Java are expressions Methods that return a value can be use as terms in an expression just like variables and constants and those that don t can be used on their own The Math class in the java1ang package de nes several methods that are useful in writing mathematical expressions Suppose for example that you need to compute the distance from the origin to the point xy which is given by y2 You can apply the square root function by calling the sqrt method in the Math class like thls double distance Mathsqrt x x y Y Static Method calls on the Math Class You ha your rst Java program ln Chapter y u hav A Quick Overview of Methods ve been working with methods ever since you wrote 39 Most of the programs e seen have used method calls such as println an setColor At the most basic level a method is a sequence of statements that has been collected together and given a name The name makes it possible to execute the statements by just providing the method name The following terms are useful when learning about methods 7 Invoking amethod using lts name ls known as callingthatm o e A method call ls preceded by elther this an Obj name and e dot operator 7 The caller can pass information to a ect name or a class method by using arguments when a method completes lts operation lt returns to lts caller on the llne ltwas called 7 A method can pass lnformatlon to the caller by returning a result Static Class Methods Recall the keyword static used when de ning named constants This keyword is also used when de ning certain methods When static is used in a method de nition a method can be called by using the following pattern ClamName metl iodName argument list Note thatyou need to include the name of the clam before a static method name Methods ike Mathsqrt are called static methods and ar de ned with the keyword static in the de nition as shown below public static double sqrtdollb1e x Writing Your Own Methods The general form ofa method de nition is scope type name parameterdeelamtlan 112 d statementsm the method 0 y where scope indicates who has access to the method type indicates the return type name is the identi er of the method and parameter declaration list is a ist of declarations of variables that are local to the method All methods must be de ned directly inside the class braces do not de ne methods inside the curly braces of other methods Writing Your Own Methods scope We name parameter declaration list natementr in the method body I The rst line in the method declaration above is called the method header line or signature I The most common value for scope is private which means that the method is available only within is own class If other classes need access to it scope should be public Ifrcope is pu lic you are exporting the method for other programmers to use I Ifamethod does not return a value We should be void I To return a value from a method you must include a return statement in the method body Writing Your Own Methods multiplies given number by 2 private int doubleNumint n etur Constructor of UseDouble class calls doubleNum public UseDouble this start int num thisdoubleNum 3 I The int n inside the parentheses is a parameter I The this double um inside the constructor is a call to the doubleNum method I The 3 inside the parentheses is an argument Parameters declare local variables Pammeter lisw contain pairs consisting of type names followed by identi ers These identi ers are local variable nam es Calling a method with an argument list is exactly the same as initializing each of the local variables declared in the parameter list Whenever you are considering local variable names within a method you must also consider each parameter name to be a local variable Methods that Return Values You can return a value from a method by including a return statement inside the method body which is usually written as return ewresn39on where expression is a Java expression that speci es the value you want to return of the type speci ed in the method header As an example the method de nition private double EeetroInchesdoub1e feet etuzn INCHESINFODT It feet converts a distance in feet to the equivalent number of inches relying on the fact that there are 12 inches in a foot and that lNCHESilNiFOOT is a named constant set equal to 12 Writing Your Own Methods return the result of 2nz private int nX2PlusZint n int 2 return 2 n constructor of UsenXZPlusZ public Usenx2Plusz thisstart thisprint1nquotquotthisnX2P1usZ34 The int n int 2 inside the parentheses are parameters The this nx2Plusz inside the constructor is a call to the nx2 Plusz method The 3 and 4 inside the parentheses are argumentr Mechanics of the MethodCalling Process When you call a method the following actions occur t list in the method call is evaluated in the th d l The argumen context of the calling me o 2 L Each argument s value is copied into the corresponding parameter variable Assignment follows the order in which the arguments appear the st argument is copied into the rst parameter variable and so on The statemenw in the method body are evaluated in sequence If a return statement is run the return value is computed and substituted for the method call in the calling method Execution continues from where it le off in the calling me o Methods Involving Control Statements 0 The body of a method can contain statements of any type including control statements As an example the following method uses an if statement to find the larger of two values private int maXint X int y if xgty return X else return y As this example makes clear return statements can be used at any point in the method and may appear more than once Once a return statement is executed no statements below the return statement are executed Methods Returning Objects The text includes examples of methods that return graphical objects The following method creates a lled circle centered at the point x y with a radius of r pixels which is lled using the specified color private GOval createFilledCircledouble X double y double r Color color GOval circle new GOvalX r y r 2 r 2 r circle setFilledtrue circle setColor color return circle If you are creating a GraphicsProgram that requires many filled circles in different colors the createFilledCircle method can be called multiple times to save a considerable amount of code Using Predicate Methods Effectively New programmers often seem uncomfortable with Boolean values and end up writing inelegant code For example a beginner might write isDivisibleBy like this private boolean isDivisibleByint X int y if X y 0 return true else return false While this code is not technically incorrect it is inelegant enough to deserve the bug symbol Methods returning nonnumeric types Methods in Java can return values of any type The following method for example returns the English name of the day of the week given a number between 0 Sunday and 6 Saturday private String weekdayNameint day switch day case 0 return quotSundayquot case 1 return quotMondayquot case 2 return quotTuesdayquot case 3 return quotwednesdayquot case 4 return quotThursdayquot case 5 return quotFridayquot case return quotSaturdayquot default return quotIllegal weekdayquot O I String is a class defined in the javalang package Hence the leading capital letter in the typename String Predicate Methods 0 Methods that return Boolean values play an important role in programming and are called predicate methods As an example the following method returns true if the first parameter is evenly divisible by the second and false otherwise private boolean isDivisibleByint X int y return X y 0 Once you have defined a predicate method you can call it anywhere you need a boolean value For example you can print the integers between 1 and 100 that are evenly divisible by 7 as follows for int i l i lt 100 i if thisisDivisibleByi 7 thisprintlni Using Predicate Methods Effectively A similar problem occurs when novices explicitly check to see if a predicate method returns true You should be careful to avoid such redundant tests in your own programs for int i l i lt 100 i if thisisDivisibleByi 7 true thisprintlni 3 While this code is not technically incorrect it is inelegant enough to deserve the bug symbol Methods that Return Nothing If a method doesn t return anything you specify its return type as void A very simple method that returns nothing is shown below private void printDirectionsO hisprintlnquotWelcome to my programquot thisprintlnquotTo get started click quot quotanywhere in the windowquot This quotvoidquot method would be called by the statement this printDirections in either the constructor or in some other method in the same class body Instead o a return value this method has a side e ect printing text to the console Exercise Testing Powers of Two I Write a predicate method called isPowerofTwo that de nes an inte er ammeter called n an returns true ifn is apower oftwo and false otherwise The powers of2 are l 2 4 8 16 32 and so forth numbers that are less than or equal to zero cannot be powers of two private boolean isPowerOfTwoint n 39f n lt 1 return fa 5e while n gt 1 if n 1 2 1 return false n 2 return true The Combinations Function To illustmte method calls the text uses a function Cn k that 39on w 39 39 b computes the combinations functi hich is the num er of ways one can select k elemenw from a set ofn objects I Suppose for example that you have a set of ve coins a penny anickel a dime a quarter and a ol ar How many ways are there to select two coins penny nickel nickel dime dime quarter quarter dollar penny dime nickel quarter dime dollar penny quarter nickel dollar penny dol ar for a total of 10 Ways The factorial Method I The factorial ofa number n which is usually written as n in mathematics is de ned to be the product of the integers from lupto n Thus 5 is equal to 120 which is 1x2x3x4x5 I The following method de nition uses a for loop to compute the factorial inction private int actoria1int n int res it 1 Eor int i 11 lt n i result i i return result Decompos1tion One of the most important advantages of methods is that they make it possible to break a large task down into simpler pieces a process called decomposition Complete Task Subtask 1 Subtask Z Submsk 3 Once you have completed the decomposition you can then write a method to implement each subtask Combinations and Factorials Fortunately mathematics provides an easier way to compute s function un 39 e wa s e the combination than by co ting all th y Th value of the combinations function is given by the formula n Cquot k k x nek I Given that you already have a factorial method it is easy to turn this formula directly into a Java method as follows private int combinationsjnt n int k return factorialn factorinlrk factorialn e k Choosing a Decomposition Strategy How do you decompose large tasks into smaller ones If the realworld problem has natural subdivisions those subdivisions usually provide a useful basis for designing the program decomposition Each subtask in the decomposition should perform a single e function that is easy to name and descrlb One of the primary goals of decomposition is to simplify the programming process A good decomposition strategy must therefore limit the spread of complexity As a general rule each level in the decomposition should take responsibility for certain details and avoid having those details percolate up to higher levels Using Pseudocode Although the constructor public DrawTrainO Draw the engine Draw the boxcar Draw the caboose suggests the decomposition for the DrawTrain program it is not legal Java code being a combination of English and Java Such informal descriptions are called pseudocode It is important to remember that you don t need to implement each of the steps before you can turn this pseudocode into legal Java Each of the English lines will simply be a method call All you need to do at this point is give each method a name and decide what arguments those methods need Looking for Common Features Another useful strategy in choosing a decomposition is to look for features that are shared among several different parts of a program Such common features can be implemented by a single method In the DrawTrain program every train car has a common structure that consists of the frame for the car the wheels on which it runs and a connector to link it to its neighbor 7 The engine is black and adds a smokestack cab and cowcatcher 7 The boxcar is colored as specified by the caller and adds doors 7 The caboose is red and adds a cupola l a v Lly gf You can use a single drawCarFrame method to draw the common parts of each car as described in the text Drawing a Train As its primary illustration of decomposition the text uses the problem of writing a GraphicsProgram to draw a train 8 8 8 Dramram Although it would be possible to write a single constructor to draw the necessary graphical objects such a program would be very dif cult to read Fortunately the problem has a natural decomposition at least at the rst level public DrawTrainO Draw the engine Draw the boxcar Draw the caboose Parameters for Drawing Train Cars The DrawTrain program in the text makes the following assumptions 7 The caller will always want to supply the location of each car 7 All train cars are the same size and have the same basic structure 7 Engines are always black 7 Boxcars come in many colors which means the caller must supply it 7 Cabooses are always red These assumptions imply that the headers for drawEngine drawBoxcar and drawCaboose will look like this private void drawEnginedouble x double y private void drawBoxeardouble x double y Color color private void drawCaboosedouble x double y Algorithmic Methods Methods are important in programming because they provide a structure in which to express and encapsulate algorithms Algorithms are abstract expressions of a solution strategy Implementing an algorithm as a method makes that abstract strategy concrete Algorithms for solving a particular problem can vary widely in their ef ciency It makes sense to think carefully when you are choosing an algorithm because making a bad choice can be extremely costly Section 55 in the text looks at two algorithms for computing the greatest common divisor of the integers x and y which is de ned to be the largest integer that divides evenly into both BruteForce Approaches 0 One strategy for computing the greatest common divisor is to count backwards from the smaller value until you nd one that divides evenly into both The code looks like this private int gcdint x int y int guess Mathminx y while x guess 0 y guess 0 guess return guess This algorithm must terminate for positive values of x and y because the value of guess will eventually reach 1 At that point guess must be the greatest common divisor because the while loop will have already tested all larger ones Trying every possibility is called a bruteforce strategy How Euclid s Algorithm Works If you use Euclid s algorithm on 1000005 and 1000000 you get the correct answer in just two steps which is much better than the million steps required by brute force Euclid s great insight was that the greatest common divisor of x and y must also be the greatest common divisor of y and the remainder of x divided by y He was moreover able to prove this proposition in Book VII of his Elements It is easy to see how Euclid s algorithm works if you think about the problem geometrically as Euclid did The next slide works through the steps in the calculation when x is 78 and y is 33 The End Euclid s Algorithm 0 If you use the bruteforce approach to compute the greatest common divisor of 1000005 and 1000000 the program will take almost a million steps to tell you the answer is 5 0 You can get the answer much more quickly if you use a better algorithm The mathematician Euclid of Alexandria described a more ef cient algorithm 23 centuries ago which looks like this private int gcdint x int y int remainder x y while remainder 0 x y y remainder remainder x y return y An Illustration of Euclid s Algorithm Step 1 Compute the remainder of 78 divided by 33 y12129 Step 3 Compute the remainder of 12 divided by 9 x y n Step 4 Compute the remainder of 9 divided by 3 x E y Because there is no remainder the answer is 3 CHAPTER 2 ramming by Example Example is always more ef cacious than precept iSamuel Johnson Ramelax 1759 CMPU l 01 Computer Science I ProblemSolving and Abstraction Fall 2008 Jennifer Walter adapted from slides by Eric Roberts The Hello World Program in Java The next slide simulates the operation of HelloProgram so that you can get a sense of what appears on the display File HelloProgramjava This progranldisplays quothello worldquot on the screen It is inspiredby the firstprogranlin Brian Kernighan and Dennis Ritchie39s classic book The C Programming Language import acmgraphics import acmprogram public class HelloProgram extends GraphicsProgram public void run addl new GLabel quothello worldquot 100 75 Perspectives on the Programming Process In his Pulitzerprizewinning book computer scientist Douglas Hofstadter identi es two a A concepts holism and reductionism that turn a out to be important as you begin to learn about t programming 6 Hofstadter explains these concepts in the form of conumscmmtxcaz a dialogue in the style of Lewis Carroll Achilles I Will be glad to indulge both of you if you will rst oblige me by telling me the meaning of these strange expressions holism and reductionism Crab Holism is the most natural thing in the world to grasp It s simply the belief that the Whole is greater than the sum of its parts No one in his right mind could reject holism Anteater Reductionism is the most natural thing in the world to grasp It s simply the belief that a Whole can be understood completely if you understand its parts and the nature of their sum No one in her left brain could reject reductionism The Hello World Program One of the important in uences on the design of Java was the C programming language which was developed at Bell Labs in the early 19705 The primary reference manual for C was written by Brian Kernighan and Dennis Ritchie On the rst page of their book the authors suggest that the rst step in learning any language is to write a simple program that prints the message hello world on the display That advice remains sound today 11 Getting Started The only way to learn a new programming language is to write programs in it The first program to write is the same for all languages Print the words hello world This is the big hurdle to leap over it you have to be able to create the program text somewhere compile it load it run it and find out where your output went With these mechanical details mastered everything else is comparatively easy In C the program to print hello world is include ltstdiohgt main printfquothello worldquot The Hello World Program in Java import acmgraphics import acmprogram public class HelloProgram extends public void run addl new GLabelquothello worldquot 100 75 GraphicsProgram i 8 8 8 HelloProgram hello world A Program to Add Two Numbers The next slide animates the operation of this program to illustrate the assignment of values to variables import acmprogram public void run int n1 readIntquotEnter n1 int n2 readIntquotEnter n2 int total n1 n2 public class Add2Integers extends ConsoleProgram printlnquotThis program adds two numbersquot printlnquotThe total is quot total quotquot quot quot The Add2 Integers Program class Add2Integers extends ConsoleProgram public void run printlnquotThis program adds two numbersquot int n1 readIntquotEnter n1 quot Programming Idioms and Patterns Experienced programmers also often take a holistic approach to programming Effective programmers can recognize a variety of common operations and have learned a standard solution strategy for each one The code that implements such a solution strategy is called a programming idiom or programming pattern Learning to use these patterns saves you from having to think about the nittygritty details int n2 readIntquotEnter n2 quot int total n1 n2 printlnquotThe total is quot total quotquot n1 n2 total 17H25H42 8 O 8 AddZIntegers This program adds two numbers Enter n1 17 Enter n2 25 The total is 42 Classes and Objects 0 As described in the slides for Chapter 1 Java programs are written as collections of classes which serve as templates for individual objects Each object is an instance of a particular class which can serve as a pattern for many different objects 0 Classes in Java form hierarchies Except for the class named Object that stands at the top of the hierarchy every class in Java is a subclass of some other class which is called its superclass A class can have many subclasses but each class has only one superclass A class represents a specialization of its superclass If you create an object that is an instance of a class that object is also an instance of all other classes in the hierarchy above it in the superclass chain 0 When you define a new class in Java that class automatically inherits the behavior of its superclass Biological Class Hierarchy Kingdom Phylum Class Order Family Classi cation of the red ant V Note that there can be many Iridamyrmexpurpureus individual red ants each of which is an instance of the I b 39 1 Genus 3mm same as1c c ass kw Species 0 As an example it is important to think of a statement like int n1 readIntquotEnter n1 quot not in terms of what each part of the statement means but rather as a holistic pattern to read an integer from the user int variable readIntquotpromplquot The structure of Java s class hierarchy resembles the biological classification scheme introduced by Scandinavian botanist Carl Linnaeus in the 18th century Linnaeus s contribution was to recognize that organisms fit into a hierarchical classification scheme in which the placement of individual species reflects anatomical similarities Biological Models of Class Structure Carl Linnaeus 1707 1778 The Program Hierarchy Java class hierarchies are similar to the biological class Applet hierarchy from the previous slide This diagram for example shows the hierarchy formed by the classes in the acm program package JApplet Program Every ConsoleProgram is also a Program a JApplet and an Applet That means that every ConsoleProgram can run as an applet on the web ConsoleProgram Di a1 ogProgram GraphicsProgram The DialogProgram Class In objectoriented languages like Java a class de nition speci es the behavior of objects of that class The DialogProgram class has exactly the same operations as the ConsoleProgram class the only difference is that the input and output operations use popup dialogs instead of a console as illustrated by the following implementation of AddTonntegers public class AddZIntegers extends DialogProgram public void run printlnquotThis program adds two numbersquot int n1 readIntquotEnter n1 quot int n2 readIntquotEnter n2 quot int total n1 n2 printlnquotThe total is quot total quotquot Sending Messages to Objects In many applications you will need to change the appearance of a graphical object after you have created it For example you might want to have the object change its color or move to a new position on the canvas In objectoriented languages like Java such changes are the responsibility of the object To change the color of an object you send a message to the object asking it to change color Java uses the following syntaX to send a message to an object receiver name arguments where receiver is the object to which the message is directed name identi es the type of message and arguments is a list of values used to specify any other information associated with the message The Java Coordinate System Positions and distances in a graphics program are measured in terms of pixels which are the individual dots that cover the screen Unlike traditional mathematics Java de nes the origin of the coordinate system to be in the upper left corner Values for the x coordinate increase as you move right across the screen y coordinate values increase as you move down Creating a GLabel at a particular x and y position means that the baseline of the rst character in the label appears at that point as follows 6 0 6 Helloprogram oo75gtHeo Graphical Programs The GraphicsProgram class makes it possible to create simple pictures on the screen The conceptual model is that of a collage composed of objects on a canvas Running a GraphicsProgram creates a window that serves as the background canvas for the collage You create pictures by creating graphical objects of various kinds and then adding those objects to the canvas In chapter 2 you learn how to work with labels rectangles ovals and lines using the classes GLabel GRect GOval and GLine The complete set of graphics classes is introduced in Chapter 9 Sending Messages to a GLabel The following program illustrates sending a message to an object Note that the label doesn t appear until it is added to the canvas public class HelloProgram extends GraphicsProgram public void run GLabel label new GLabelquothello worldquot 100 75 label setE ontquotSansSerif 36quot label setColor ColorRED addlabel l label hello world S 8 8 Helloprogram hello world slap tmulanon The GObj ect Hierarchy The classes that represent graphical objects form a hierarchy part of which looks like this GObj ec t GL abel GRec t j GOval GLine Operations on graphical objects are de ned at each level of the hierarchy Operations that apply to all graphical objects are speci ed at the GObj ect level where they are inherited by each subclass Operations that apply to a particular subclass are speci ed as part of the de nition of that class Operations on the GObject Class The following method calls can be made on all GObj ects object setColor color Sets the color of the object to the speci ed color constant object setLocation x y Changes the location of the object to the point x y object move dx dy Moves the object on the screen by adding dx and dy to its current coordinates The standard color names are de ned in the java awt package Color BLACK Color RED Color BLUE Color DARKGRAY Color YELLOW Color MAGENTA Color GRAY Color GREEN Color ORANGE Color LIGHTGRAY Color CYAN Color PINK Color WHITE Drawing Geometrical Objects Calls to constructors of Grect Goval and GLine Operations on the GLabel Class Call to Glabel constructor new GLabeltext x Creates a label containing the speci ed text that begins at the point x y Call to method setFont of the GLabel class label setFont font Sets the font used to display the label as speci ed by the font string The fontis typically speci ed as a string in the form quot family style sizequot where family is the name of a font family Times Monospaced style is either PLAIN BOLD ITALIC or BOLDITALIC size is an integer indicating the point size The GRectPlusGOval Program new GRect x y width height Creates a rectangle Whose upper le corner is at x y of the speci ed size new Goval x y width height Creates an oval that ts inside the rectangle With the same dimensions new GLine x0 yo x1 y1 Creates a line extending from x0 ya to x1 y1 Call to methods de ned in the GRect and GOval classes object setFilled ll lffi ll is true lls in the interior ofthe object iffalse shows only the outline public class GRectPlusGOval extends GraphicsProgram public void run G ect rect new GRect100 50 125 60 rectsetFilledtrue rectsetColorColorRED addrect Goval oval new Goval100 50 125 60 ovalsetFilledtrue ovalsetFillColorColorGREEN add Oval r rect oval object setFillColor color Sets the color used to ll the interior which can be different from the border The End 398 8 8 Gaenmuscova slap Simulation onarren a 1 gs and Characters Sn yy ldm39ttlmkthtmrrbmmasmumm aswods rmmmmsmmxgm mm mrmnmaaa ml CMPUlOl Computer Science I ProblemSolving and Abstraction Fall 2008 Jennifer Walter adapted from slldes by Erlc Roberts The ASCII Subset of Unicode The following table shows the rst 128 characters in the Unicode character set which are the same as in the older ASCII scheme Special Characters Special characters are typically used to control formatting Special characters are indicated in the Unicode table by an escape sequence which consists of a backslash followed by a nes are character or sequence of diglm T e common 0 Characters Characters are stored as integers If you assign an integer to each character you can use that integer as a code for the character it represents Character codes however are not particularly useful unless they are standardized If different computer manufacturers use differen co ing sequences as was indeed the case in the early years it is harder to share such data across machines The rst widely adopted character encoding was ASCII American Standard Code for Information Interclmnge With only 256 possible characters the ASCII system proved inadequate to represent the many a habem in use throughout world It has therefore been superse ed y Unicode which allows for a much larger number of characters Notes on Character Representation The important observation on the table on the last slide is that a character ha a numeric representation and not what that representation happens to be To specify a character in a Java program you need to use a character constant which consists of the desired character enclosed in single quotation markr T us the constant 39A39 in a program indicates the Unicode representation for an uppercase A Two properties ofthe Unicode table are worth special notice 7 he character codes forthe dlglts o 9 are consecutlve r The letters ln the al habet are divided lnto two ranges one for the uppercase letters and one forthe lowercase letters Wlthln each range a z and A z the Unlcodevalues are consecuthe Methods in the Character Class Character Arithmetic The fact that characters have underlying representations as integers allows you can use them in ari 39c expressions For example if you evaluate the expression 39A39 1 ava will convert the character 39A39 into the integer 65 and then add 1 to get 66 which is the character code for 39B 39 As an example the following method returns a randomly chosen uppercase letter note the cast operation return char rgennextInt39R39 39239 public char randomLetter The following code implements the isDigit method from the Character c ass39 public boolean isDigitchar ch return ch gt 39039 ampamp ch lt 39939 Strings as an Abstract Idea Ever s39nce the very rst program in the text which displayed the mess e quothello worldquot on the screen you have been using strings to communicate with the user Up to now you have not had any idea how Java represents strings inside the computer or how you might manipulate the characters that make up a strin At e same time e fact that you don t know those things has not compromised your ability to use strings effectively because you have been able to think of strings holistically as if they were a primitive type For most applications the abstract view of strings you have t held up o now is precis ly the rig t one On the inside strings are surprisingly complicated obj ecw whose details are better le hidden Java supports a highlevel view of strings by making Stri ng a class whose methods hide the underlying comp exity Strings vs Characters The differences in the conceptual model between strings and characters can be illustrated by exarnp e Both the String and the Character class export a toUpperCase method that converts lowercase letters to their uppercase equivalenw In the Character class you call toUpperCase as a static method like this ch charactertoUpperCasech In the String class you apply toUpperCase to an existing string as follows str strtoUpperCase Note that both classes require you to assign the result back to the original variable if you want to reset its value Exercise Character Arithmetic the appropriate letter in the range 39A39 through 39E If the argument is ouwide this range the method should return 39 39 Using Methods in the String Class I Java de nes many useful methods that operate on the Stri ng class Before trying to use those methods individually it is important to understand how those methods work at a more general level I The String class uses the receiver syntax when you call a method on a string Instead of calling a static method as you do for example with the Character c ass Java s model is that you send a message to a string object I None ofthe methods in Java s String class change the value of the string used as the receiver What happens instead is that these methods retum a new string on which the desired changes have been performed I Classes that prohibit clients from changing an object s state are said o be immutable Immutable classes have man advantages and play an important role in programming Selecting Characters from a String Conceptually a string is an ordered collection of characters In Java the character positions in a string are identi ed by an index that begins at 0 and extends up to one less than the length of the string For example the characters in the string quothello worldquot are arranged like this main ul23456789mn I You can obtain the ofchars in String str str length I You can select an individual character by calling charAt Ir where kis the index of the desired character The expression strcharAt0 returns the rst character in 5 tr which is at index position 0 in the above example this would return the char 39h39 Concatenation If you use with numeric operands it signifies addition If at least one of the operands is a string Java interprets as concatenation When it is used in this way Java performs the following steps If one of the operands is not a string convert it to a string by applying the toString method for that class or boxing a primitive value by converting it to its corresponding wrapper class and then using the toString method Concatenate the resulting strings Checking Str1ngs for Equality Many applications will require you to test whether two strings are equal in the sense that they contain the same characters Although it seems natural to do so you cannot use the operator for this purpose While it is legal to write ifsl52 the if test will not have the desired effect When you use on two objects it checks whether the objects are identical which means that the references point to the same address What you need to do instead is call the equals method if 51 equals 52 Searching in a String J ava s String class includes several methods for searching within a string for a particular character or substring The method indexOf takes either a string or a character and returns the index within the receiving string at which the first instance of that value begins If the string or character does not exist at all indexOf returns 1 For example if the variable str contains the string quothello worldquot str indexof 39h39 returns 0 str indexof quot oquot returns 4 str indexof quotellquot returns 1 str indexof 39 x39 returns 1 The indexOf method takes an optional second argument that indicates the starting position for the search Thus strindexof quot0quot 5 returns 8 Extracting Substrings The substring method extracts a piece of a larger string using index numbers With only one argument the method returns the substring from the given position to the end The general form of the subs tring call is str substring p1 p2 where p1 is the first index position in the desired substring and p2 is the index position immediately following the last position in the substring As an example if you wanted to select the substring quotellquot from a string variable str containing quothello worldquot you would make the following call str substring 1 4 Comparing Characters and Strings The fact that characters are primitive types with a numeric internal form allows you to compare them using the relational operators If cl and c2 are characters the expression is true if the Unicode value of cl is less than that of c2 The String class allows you to compare two strings using the internal values of the characters although you must use the compareTo method instead of the relational operators sl compareTo 2 This call returns an integer that is less than 0 if s1 is less than s2 greater than 0 if s1 is greater than s2 and 0 if the two strings are equal Other Methods in the String Class int lastIndexOf char ch or lastIndexOf String str Returns the index of the last match of the argument or 1 if none exists boolean equals IgnoreCase String str Returns true if this string and str are the same ignoring differences in case boolean startsWith String str Returns true if this string starts with str boolean endsWi th String str Returns true if this string starts with str String replace char cl char 02 Returns a copy of this string with all instances of cl replaced by c2 String trim Returns a copy of this string with leading and trailing whitespace removed String toLowerCase Returns a copy of this string with all uppercase characters changed to lowercase String toUpperCase Returns a copy of this string with all lowercase characters changed to uppercase Simple String Idioms When you work with strings there are two idiomatic patterns that are particularly important 1 Iterating through the characters in a string for int i 0 1 lt strlengthr39 i char ch strcharAt i ccee upmcess each character In turn 2 Growing a new string character by character String result W for whatever mats are appmpnate u the appllcatzun c etc deterrhzhethe nextcharactzrm be ad e result h A Case Study in String Processing Section 85 works through the design and implementation of a program to convert a sentence from English to Pig Latin At least for this dialect the Pig Latin version of a word is formed by applying the following rules 1 If the word begins with a consonant you form the Pig Latin version by moving the initial consonant string to the end of the word and then adding the suffix try as follows scram 4 amscray If the word begins with a vowel you form the Pig Latin version simply by adding the suffix way like this apple 4 appleway The book shows how to make aPig Latin translator using a class called StringTokenizer Iprovide adifferent implementation in the notes and 1 don39t require you to know how to use the StringTokenizer lass Designing translateLine The translateLine method must divide the input line into words translate each word and then reassemble those words The following is analgorithm for tv n 1 I f 139 n set result string to the empty string set i to 0 while i lt length of line create an empty string called word while the character t sition i 39 line is a letter a end he etter at position i onto wo increment i translate the word into its Pig Latin equivalent append word to result string if i lt length of line append character onto result string increment I return result Exercise String Processing I How would you implement toUpperCase str so it returns an uppercase copy of str Hint use patterns 1 and 2 and the Character method toUpperCase Starting at the Top I In accordance with the principle of topdown design it makes sense to start with the constructor which has the following pseudocode form public lzigLatino Teh the deer what the program does Ask the e for a he 11me Trahezate the Ice mm Pie Lash ahdpnht It ah the console I This pseudocode is easy to translate to Java as long as you are w1 mg 0 include a c l to a metho you have not yet written tmnslateLine note the readLine method mimic yinLatino lt Hassle s glam translate a line intn Ply Latins string line lmsaeadltnlz ilnln a line it unipxnmlntuns trmiatetineuinen The translateLine Method private string translateLinestring line string to be returned string result 39 t i 0 loop counter 1n whilei lt linelenqth string word string to hold each word while i lt linelength ampamp CharacterisLetterlinecharBti word linecharnti i what conditions must hold after whilev word thistranslateWordword to do result word if i lt linelength space or punctuation result linecharnti i ireth result Now we39ve tackled translateLine but how do we write translateWord The translateWord Method The translateWord method consists of the rules for forming Pig Latin words translated into Java private String translateWordString word int find vp irstVowelword to do if vp 1 no vowels in word return word else if vp 0 first char is vowel return word quotwayquot else split word before first vowel wordsubstring0 vp wordsubstringvp return tail head quotayquot This method assumes that a word is composed of only letters Now we have one more method to write to complete our Pig Latin translator findFirstVowel string The reverseString Method public void reverseString th isprintlnquotThis program reverses a string quot String str thisreadLinequotEnter a string quot String rev thisreverseStringstr thisprintlnstr quot spelled backwards is quot rev rev str s s e Heuersesmng This program reverses a string Enter a string STRESSED STRESSED spelled backwards is DESSERTS slap tmulmton The f indFirstVowel Method The findFirstVowel method iterates through the given String returning the numeric position of the rst vowel or 1 if no vowels are found private int findFirstVowelString word for int i 0 i lt wordlength i switch CharactertoLowerCasewordcharAti cae39 c equot se i c e39o case39u39 return i return 1 no more to do Note the use of Character toLowerCase word charAt i method that converts the character at position i in the given input string to lower case Why is this needed The End CHAPTER II zys CMPUlOl Computer Science I ProblemSolving and Abstraction Jennifer Walter adapted from slldes by Erlc Roberts Declaring an Array Variable As with any other variable array variables must be declared before you use them In Java the most common syntax for declaring an array variable looks like this type name new typehl where type is any data type name is the array object name and n is an integer expression indicating the number of elements This declaration syntax combines two operations The part the line to the le ofthe equal sign declares the variable the part to the right creates an array Va ue wi e speci ed number of elemenm and then assigns it to the array variable Even though the two operations can be distinct it will help you avoid errors if you make a habit of initializing your arrays in the same statement in whichyou declare them Element Selection with Arrays Given an array such as the intArray variable declared on the last slide shown below you can access the value of any 1 t y writing the index of that element in brackets after the array name This operation is called selection You can for example select intArray subzero by writing Each position in the array is an int variable so you can assign lt a new value The following statement changes the value of intArray subnine to 42 jntmay942 Introduction to Arrays An array is the simplest collection of individual data values and has two main distinguishing characteristics 1 An array is ordered indexed and has a xed length that must be speci ed when the array is created 2 An array is homogeneous Every element in the array must have the same type although it can be any type The individual values in an array are called elements The ose elements is called the element type The xed number of elements is called the length of the array Each element is identi ed by its position number in the array which is called is index 0 to length1 Arrays are not fullblown objects because they have no methods They are a special form exception to rules An Example of Array Declaration The following declaration creates an array called intArray consisting of 10 values oftype 1m intl inmrray new int10 This easiest way to visualize arrays is to think of them as a linear collection of boxes on the heap each of which is 39th its index number You might therefore diagram the intArray variable by drawing something like this manna 0 III 0 II Java automatically initializes each element of a newly created arr t its default vaue w ic is zero for numeric types fal se for values oftype boolean and null for objects Iterating through Array Elements In many cases it is useful to have the index of an array be the control variable ofa for loop dard for loop pattern that cycles through each of the array ls The Stan elanents ln tum looks llke th for int i o lt arraylength i i Operaauns involving the 1quot element afthe army aay1ength ls the number of elements in the array Note that length ls not a method as lt ls ln Strlngs u can reset every element in intArray to 2 using the following for loop inmrray i for int i o i lt intnrraylength i 2 Exercise Summing an Array Write a method sumArray that takes an array of integers and returns the sum of those values Passing Arrays as Parameters When you pass an array as a parameter to a method or return a method as a result only the reference to the array on the stack is actually passed between the methods If a method changes an element of an array passed as a parameter that change will persist after the method returns just like an object that is passed as a parameter to a method The next slide contains a simulated version of a program that performs the following actions 1 Creates an array containing the integers 0 to n l 2 Prints out the elements in the array 3 Reverses the elements in the array 4 Prints out the reversed array on the console Initializing Arrays Java makes it easy to initialize the elements of an array as part of a declaration The syntax is type name elements where elements is a list of the elements of the array separated by commas The length of the array is automatically set to be the number of values in the list For example the following declaration initializes the variable powersOfTen to the values 10 101 102 103 and 10 int powersOfTen llOlOOlOOOlOOOO This declaration creates an integer array of length 5 and initializes the elements as speci ed Internal Representation of Arrays Arrays in Java are implemented as objects which means that they are stored in the heap The value stored in an array variable on the stack is simply a reference to the actual array Consider for example the following declaration double scores new double5 The variable scores is allocated on the stack and is assigned the address of a newly allocated array in the heap heap stack length 5 mm scoresIl men scores 3 00 The ReverseArray Program public void reverseArray int n thisreadIntquotEnter number of elements quot39 int intArray thiscreateIndexArrayn this printlnquotForward quot thisarrayToStringintArray 39 this reverseArray intArray 39 this printlnquotReverse quot thisarrayToStringintArray 39 n intArray m 8 9 8 ReverseArray Enter number of elements 10 Forward 0 1 2 3 4 Reverse 9 8 7 6 57 slap tmulmton Constant Lookup Tables An application of simultaneous array initialization and declaration is to create constant arrays used to look up a value by its index number Such arrays are called lookup tables As an example suppose that you are using the integers 1 through 12 to represent the names of the months from January to December You can easily convert these integers to the corresponding month name by declaring the following table private static final String MONTHNAMES null Included because there is no month 0 quotJanuaryquot quotFebruaryquot quotMarchquot quotAprilquot quotMayquot I quotJunequot I quotJulyquot I quotAugustquot I quotSeptemberquot quotOctoberquot quotNovemberquot quotDecemberquot l You can then use the expression MONTHNAMES month to get the names of the given month an integer Multidimensional Arrays Because the elemenw of an those elements c elve arr can be of any Java type an thems s called multidimensional arra ay be arrays Arrays of arrays are ys In Java you can create a multidimensional array by using multiple brackew in both the type and the initialization parts of the dec aration For example you can create array space for a 3x3 tictactoe board using the following declaration cha board new charm 31 This declaration creates a twodimensional array of characters that is organized like this Initializing 2dimensional Arrays A much more common technique for Working With 2 dimensional arrays is using a nested forloop For example you can initialize a multiplication table for the digits 0 to 9 like this private int multiplication l ableint n intn 1 tab1e new intth n for int i o i lt n iH for int j 0 j lt n j tab1ei391 i I j i return table Tabulation Arrays and ArrayLists are useful When you have a set of data values and need to count h many values fall into each of a set ofranges This process is called tabulation Tabulation uses these collections in a slightly different Way from those applications that use them to store a list of data en you implement a tabulation rograrn you use each data value to compute an index into a collection thatkeeps track of how many values fall into that category The example of tabulation used in the text on page 429 is a program that counts hoW many times each of the 26 letters appears in a sequence of text lines using an array or tabulation Such a program W be very useful in solving 39 39d 0 codes and c1phers as described on the next Sll e Initializing Multidimensional Array s You can initialize a multidimensional array When you declare it by using nested braces to re ect the levels of array nesting I For example ou can declare and initialize a multiplication table for the digits 0 to 9 like this private static int MULTIPLICATIDNTAELE 0 0 0 0 1 0 1 0 o o 1 i 01 11 21 31 41 51 51 71 31 9 1 o 2 4 6 a1o1214161a 1 i o 3 6 91215 1a 21 24 27 1 i o 4 a 12 16 2o 24 2a 32 36 1 i o 5 1o 15 2o 25 3o 35 4o 45 1 i o 6 12 1a 24 3o 36 42 4a 56 1 i o 7 14 21 2a 35 42 49 56 63 1 i o a 16 2432 40 4856 64 72 1 i o 9 13 2736 4554 63 72 81 1 Printing 2dinlensional Arrays I A er creating the multiplication table on the last slide you 39 d could print it as shown in the followmg metho private void printnrrayint table for 39 39 39 table1ength 1 for int j a j lt tab1ei1ength j thisprintquot quottab1eij I thisprint1n I Note that this loop Would also Work for 2djmensional arrays in which the length of rows varies Crypto grams I A cryptogram is a puzzle in Which a message is encoded by replacing each letter in the original text with some letter The substitution pattern remains the same throughout the message Your job in solving a cryptogram is to gure out this correspondence The usual strategy for solving a cryptogram is to assume that the most common letters in the coded message correspond to the most common letters in English Which are E T A O N s H R D L and U Instead of counting each of the characters by hand it Would make thin easier if you had a program to do the job You type in the coded message and out pops a table showing hoW o en each letter appears Implementation Strategy The basic idea behind the program to count letter frequencies is to use a collection with 26 elements to keep track of how many times each letter appears As the program reads the text it increments the element that corresponds to each letter TWAS BRILLIG lMMMMMOMMMMMMWMMWMMMMMMIMMM I 1 2 3 4 5 7 8 9 1D 11 12 13 14 15 16 17 18 19 2U 15 21 22 23 24 CountLetterFrequencies CountLetterFrequencies import acmprogram kk This program creates a table of the letter frequencies in a paragraph of input text terminated by a blank line 4 public class 39 extends Private instance variable private int frequency39l able Named constant public static final int ALPHABETLENGTH 26 public void run isprintln This program counts letter frequencies thisprintln Enter text followed by a blank line ton in icate the end of the text thisinitFrequencyTable u while 1 String line thisreadLine if linelength 0 re b ak thiscountLetterFrequenciesline this printFrequencyTable Initializes the frequency table to contain zeros private void initFrequencyTable thisfrequencyTable new intALPHABETLENGTH for int i 0 i lt ALPHABETLENGTH i thisfrequencyTablei Counts the letter frequencies in a line of text private void CountLetterFrequenciesString line for int i 0 i lt linelength i ch linecharAti if characterisLetterch int 39ndex charactertoUpperCasech 39A39 this frequency39l able index Displays the frequency table private void printFrequencyTable 2 lt 39239 ch for char ch 39A39 int index ch 39A39 hr39inf39lnl h thi index main method not shown page 202 slapcodtz This example illustrates that we can make an array of any data type both primitive and object types 888 varnpanem ism 1quot W 39 r afarWV x ampamps 90 a ca x E 1 ilnii 51quot Ill m 39 39n15 III Iquot gt n u 235 g Q m 7 z m I 391391111 1 91 3 101 77 Wampuh il f l ll z l 1050 miurl 2 Sx ggx 39 NW mI Mata II 0quot 2s M x a 0014M39 W M www meg s O 39Q 00011 egg1 I m 0 war 1 391 l I I 1quot971239 11411111quot at x xdr amm I 4 IggyV n r f A geeasshmm 49 Mr en s page 1 02 nap coda Arrays and Graphics Arrays turn up frequently in graphical programming Any time that you have collections of variables of the same type an array provides a convenient structure for storing them As an aesthetically pleasing illustration of both the use of arrays and the possibility of creating dynamic pictures using nothing but straight lines the text presents the YarnPattern program which simulates the following process a Place a set of pegs at regular intervals around a rectangular border 7 Tie a piece of colored yam around the peg in the upper left corner a Loop that yam around the peg a certain distance DELTA ahead 7 Continue moving forward DELTA pegs until you close the loop Nsizga i 539 Qty Shades of Spironph W Batmanll lx Inn 4 end nmam The End cHAPTER 15Secllon1 trsion mbesthywwedmtk mrus mmmn ammmmmmmdncmbn CMPUlOl Computer Science I ProblemSolving and Abstraction Fa l 2 08 Jennifer Walter adapted from slldes by Erlc Roberts Static Methods Static methods are declared using the following syntax puhlic static ltxeluxnrlypegt Wlhndrnamzgt1ltpaxamzlex nstgtt in every program 39 Since main is a static method it must create a new object of its own class type before it can call any nonstatic methods Static methods cannot access instance variables or instance methods and cannot contain the keyword quotthisquot because they apply to an entire class not to a particular object in a class Reading and Printing Without acm To read from the keyboard without using the acm package you can importjavautil and use the Scanner class Scanner sc new ScannerSystemin int number sc nextIntO To print to the screen use System outprintlnquotText to output Static Methods Methods called by using the dot operator as a suf x on the name Examples of static methods we39ve used o Character class methods o Math class methods mihlic 39 p for use by other classes Static methods depend only on input parameters and cannot use any instance variables or nonstatic methods within the class Client classes can call these methods without creating an object ofthe class type Static Methods n advantage of writing static methods is that they can be easily tested from the DrJava Interactions Pane For example try typing CharactertoUpp erCas e c39 Mathpow26 in the Interactions Pane The recursive methods we will write and test in our next programs can be static because they generally depend only on the value oftheir instance variab es Recursion Recursion is the process of solving a problem by dividing it into smaller subproblems ofthe mmeform 2 types ofrecursion we will study o Generative Recursion Usually implemented by a static method containing a cm to itself The number of repetitions is controlled by an lntegerparameter Thls is an altematlve to Whlle and for oops 0 Structural Recursion Implemented wlth recurslve classes le class that contain instance varlables ofthelr own type We Will coyertnis topic next Recursive Functions The easiest examples of recursion to understand are functions in which the recursion is clear from the de nition As an example consider the factorial function which can be de ned in either of the following ways n nxnlxn2Xx3x2xl 1 ifnisO n n x n 1 otherwise The second de nition leads directly to the following code which is shown in simulated execution on the next slide public static int factorialint n if n 0 return 1 else return n factorialn 1 The Recursive Leap of Faith The purpose of going through the complete decomposition of the calculation of factorial 5 is to convince you that the process works and that recursive calls are in fact no different from other method calls at least in their internal operation Writing recursive programs becomes natural only after you have enough con dence in the process that you don t need to trace them fully As you write a recursive program it is important to believe that any recursive call will return the correct answer as long as the arguments continually get closer to a stopping condition Believing that to be trueieven before you have completed the codeiis called the recursive leap of faith Shades of Indiana Jones Batman The Recursive Paradigm What does quota base casequot mean It can be any condition that stops the recursion by returning a value Each recursive call must ensure that the input argument is closer to the base case than the current input parameter if testfor a base case mpute and return the solution without using recursion els e Divide the problem into one or more subproblems that have the same form Solve each ofthe subproblems by calling this method recursively Return the solution from the results of the various subproblems Simulating the factorial Method public static void ca 39 1 I public static int Factorial Hni n I public static int Factorial Hni n I public static int Factorial Hni n I public static int Factorial Hni n I public static int Factorial lini n I public static int factorialint n if n 0 return 1 else return n factorialn 1 n E i 966 Faaonal Enter 11 5 5 120 slap simulation The Recursive Paradigm Most recursive methods you encounter in an introductory course have bodies that t the following general pattern if testfor one or more base cases Compute and return the simple solution without using recursion els e Divide the problem into one or more subproblems that have the same form Solve each ofthe subproblems by calling this method recursively Return the solution from the results of the varioussubproblems Finding a recursive solution is mostly a matter of guring out how to break it down so that it ts the paradigm When you do so you must do two things 1 Identify base cases that can be solved without recursion 2 Find a recursive decomposition that breaks each instance of the problem into simpler subproblems of the same type which you can then solve by applying the method recursively Recursive Methods Write a recursive method to return the sum of all the numbers between 1 and n In this example the stopping case is reached when the input parameter n is equal to O Recursive Methods I Write a recursive method to return the sum of all the numbers ay in a given input arr In this example the stopping case is reached when the input parameter j is equal to the length of the array and the recursive call is made by passing in the array and j incremented by 1 bringing j closer to the stopping case Recursive Methods As a programmer you need to ensure that all recursive calls bring the execution closer to the stopping condition The simpler cases must eventually reach the stopping condition or the method will call itself infinitely In Java when a method calls itself a very large number of times the stack gets full and a quotStack Overflow I oocurs Recursive Methods I Write a recursive method to determine if a given String is a palindrome In this example there are two base cases one for even and one for oddlength palindromes The recursive call is made on the input string minus the first and last character str is closer to the empty string on every call Recursive Methods I Write a recursive method to mise a base to an exponent power These examples illustrate the essential features of a recursive me od 1 A base case With no recursive call 2 A recursive case tha contains a call to the containing method passing in an argument that is closer to the base case than the value of the current parameter Recursive Methods I Write a recursive method to reverse a String In this example the base case is reached when the length of the input string is zero The recursive call is made on the input string minus the first character str length is closer to the empty string Testing Recursive Methods I What test cases Would you use to thoroughly test this method puhlic static hnnlean isPalinixmnzistxinq m r if slxlenqth n H slxlenqth ii quotum um 15 r xetuxntstxmhnnlt b umhnmisuumgtmHip m a al39ndzmnzislxsuhslxinqtlslxlenqlhthrln Testing Recursive Methods Recursive Methods I What test cases would you use to thoroughly test this method Write a recursive predicate method that takes an array of integers as an input parameter and returns true if the numbers public void run in the array are all even tring strl quotrotatorquot odd length palindrome string str2 vquot empty palindrome string str v 3 ma dalnquot even length palindrome string str4 v omjabberquot nonepalindrome printlnstr1 v should be a palindrome and tests quot isPalindrollISstr1 printlnstr2 v should be a palindrome and tests quot isPalindrollISstr2 printlnstr3 v should be a palindrome and tests quot 39s alindromestr3 printlnstr4 v should not be a palindrome and tests w isPalindrollISstr4 Recursive Methods Recursive Methods a recursive predicate method to determine if the ce of numbers in the given array is increasing Write a recursive predicate method that takes an array of Write integers as an input ammeter and returns true if any of the sequen numbers in the array list are even in this example three mputparameterr are used in the recurswe case the array arr aninteger x to quotrememberquot the value of e last element in the array and an integer i to keep track of the position of the current element in the array The base case is reached When i is equal to the size of the array The End C H A P T E R 1 emf Harm oduction The Analytical Engine offers a new avasg and a powerful language for the purposes ofrnankind iAugusta Ada Byron Lady Lovelace 1843 CMPU 1 01 Computer Science I ProblemSolving and Abstraction Fall 2008 Jennifer Walter adapted from slides by Eric Roberts Babbage s Machines 1st Mechanical Computers Charles Babbage designed 2 machines to produce mathematical tables the Difference Engine and the Analytical Engine These machines had many of the features found in modern computers The rst attempt at building one of these machines had 25000 parts stood 8 feet high and weighed 15 tons The Science Museum in London was able to complete a fullscale Difference Engine for the 200th anniversary of his birth Charles Babbage 1791 187 1 The Birth of Modern Computing The question of who invented the modern computers is not an easy one given the competing claims for that achievement In 1939 John Atanasoff and Clifford Barry built a prototype computer at Iowa State followed by a large machine in 1942 The rst largescale computer was the Electronic Numerical Integrator and Computer ENIAC completed in 1946 under the direction of J Presper Eckert and John Mauchly at the Moore School of the University of Pennsylvania Conrad Zuse in Germany and the World War II cryptography team in England also built early computers Other important contributions during the early years include storedprogramming concept generally attributed to John von Neumann and the use of switching circuits to implement binary arithmetic proposed by Claude Shannon A Brief History of Computing Electronic computers are relatively new but mechanical computers are much older The abacus goes back almost 4000 years In the 17th century several mechanical computing devices were developed in Europe V r 7 77 a K r 7 Ir Reconstruction of 1623 Blaise Pascal s 1641 Gottfried Wilhelm von Leibniz s Wilhelm Schickard machine Pascaline machine calculating wheel ca 1671 Deutsches Museum Munich Mus e des Arts et Metiers Paris IBM 0 The most important conceptual breakthroughs however came in the early part of the 19th century Ada Byron The First Programmer Augusta Ada Byron an impressive mathematician and one of the few people who fully understood Babbage39s ideas created a program for the Analytical Engine Based on this work Lady Lovelace is now widely credited as being the rst computer programmer In 1980 the U S Department of Defense named the programming language Ada in her honor WA A Augusta Ada Byron Lady Lovelace 1815 1852 What is Computer Science Many people think computer science is the study of computers and wonder how that can be a science Computer science has more to do with the study of problem solving in which the solutions happen to use computers Computer science draws on a range of intellectual traditions that includes aspects of mathematics classical science and engineering Computer science plays an increasingly important role in other disciplines Biology Computers made it possible to map the human genome Economics Computers enable the creation of better economic models Psychology Artificial intelligence helps us to understand the brain Environment Climate models require modern computing technology Literature Computerized analysis helps resolve disputed authorship and most everything else A Brief Tour of Computer Hardware Algorithms Much of computer science involves the study of algorithms b l s In an informal sense you can think of an algorithm as Simply a procedure for solving a problem CPU C To meet its more formal de nition an algorithm must be secondary 7 Clearly and unambiguously de ned storage 00000000000 000 quotetwmk 7 E eciive in the sense that its steps are executable 7 Finite in the sense that it terminates after a bounded number of steps IO devices m emory Stages in the Programming Process Each computer system understands a lowlevel language that is speci c to that type of hardware which is called its T0 execme a program Wrmen m a hlgher39level language the machine language computer must adopt one of two strategies 7 The classical approach is to translate the higherlevel language into Nlachine language is written in 1 s and 0 s machine language This strategy is called compilation 7 A second approach is to simulate the pro ram operation without actually translating it to machine language This strategy is called inter retation Programmers typically write their software in a higherlevel p language that is easier for humans to understand Stages in the Programming Process Java uses a hybrid strategy 7 Programs are compiled into an intermediate language that serves as the machine language for the Java Virtual Machine JVM 7 Java then interprets those programs by simulating the JVM Java C C Pascal FORTRAN Perl amp Python are examples of highlevel languages The Compilation Process The Java Interpreter sawcefrte ab ect rte sawcefrte ctasx rte Include ltsldln ngt mnmnmmnnnmnnn upon nun mnqu m m m ms W M W nnnmnlnnmnnlnn nn 6 n7 an m n7 nn H nnmnnmmmnnnn man ngunn t gt mam class quotdin nn n4 nn n7 nc nn 3 pm and mu m an 6 2a c 6A 6 lenllnt Mum gt I gt I emc umbte rte mnmnmmnnnmnnn nnnmnlnnmnnlml nnmnmnmmnnnn nnlnnmnnnnnlnn mnmnmmnmnnnn nlnnnlnnmnlnnlnl 6 other abject tex and trbrarrex other ctaxxfrlex Note thls dlagram i7 72 1 m a 6 3 mumummm is a modi ed vers1on 3 m 3quot 2 quotP 3 2 of the diagram on p 12 of the text Java and the ObjectOriented Paradigm 1 2 Programming languages typically support a particular style of use which is called its programming paradigm Traditional languages like FORTRAN Pascal and C use the procedural paradigm in which the programmer defines the algorithmic operations and data structures independently Modern languages like Java tend to favor the object oriented paradigm in which the programmer de nes the algorithmic and data structure of a program in a more integrated way In Java programs are written as collections of classes which de ne data types and thereby serve as templates for individual objects Each object is an instance of a particular class a single class can serve as a pattern for many different objects Running a Java Application Steps taken by me programmer Steps taken by the user The programmerwrites the code 3 The JVM interprets the byte code which generates the desired display on the user s conso e pm and run admmwulmel rtenn wuxld 15 mm The programmer then uses a Java compiler to generate a file contaimng the byte code for the app ication mrmnrmnmrass mmnmmnmnmnnmnnnm mnmmnnmnmmmmnmmn mnmn mnmnmmnmnnm nlnnlszlacain39is512E51117 23nn Java Development Process Widget j ava Helperl j ava l Java Compiler l Widget j ar Java Virtual Machine HelperN j ava Input 4gt 4gt Output Computer Java and the WorldWide Web Part of Java s success comes from the fact that it is the first language specifically designed to take advantage of the power of the WorldWide Web which came into prominence shortly before Java s release in 1995 In addition to more traditional application programs Java makes it possible to write small interactive programs called applets that run under the control of a web browser The programs that you will see in our text run as either applications or applets which means that you can easily share them on the web The programs you will write in this class run as applications and require slight modifications from their applet counterparts Programming Process Programmer types Java source code Programmer stores source code in les Widget java Helper1java Helper2java HelperNjava Compiler translates source code into Java byte code Compiler stores byte code in le Widget class Helper1class Helper2class HelperNclass Interpreter runs compiled code on the Java Virtual Machine J VM Java Documentation 0 All existing Java classes the classes that come with any installation of the language are documented in what is known as the Java Application Programming Interface API 0 There is a link to the Java API on the course web page 0 An important part of this class will involve learning to use the Java API DrJ av a 0 Integrated Java Development Environment 0 Editor Compiler Debugger and more 0 Free version available for Windows and Macintosh 0 See link to download site on our class web page there you will see choices forWindows or Mac OS X 0 Be sure to download the Java JDK 50 along with the most recent version of DrJava acm Library After you have completed the rst half of this course we will begin to wean ourselves from dependence on the acm library First Assignment Included with the syllabus I39ve asked you to 0 check the dates of the midterm exams on the course syllabus If you will not be here for the exam please indicate the reason for your absence 0 indicate dates on which you will be absent due to religious Observances or athletic events and 0 list any computer languages you have used in the past and send your responses to me in an email message acm Library We will use the acm library in CMPU 101 to 1 Simplify the creation of graphics programs 2 Simplify readwrite operations The acm package also has its own documentation Links to download the acm jar le and to the acm API are on the course web page First Lab Friday from noon to 130 pm in OLB 104 You will learn to login on our lab computers download a starter le from the web compile and run a simple Java program and submit the results of your work ou may choose to use your own laptop in the lab I39d like a couple of volunteers to bring a laptop to the rst lab The End charm a no ressions mewmnnmnx r Wmnnani namwmtmw marinerysrnsum twoer ms m7 CMPUlOl Computer Science I ProblemSolving and Abstraction Jennifer Walter adapted from slides by Eric Roberts Primitive Data Types Although complex data values are represented using objects Java de nes a set ofprimitjve types to represent simple data Ofthe eight primitive types available in Java the programs in our text use only the followmg four int This type is used to represent integers which are whole mbe s such as 17 or753 double This type is used to represent numbers that include a decim 1 fraction such as 3 14159265 In Java such values are called floatingrpuint numbers the name double comes rom e fact tlnat the representation uses twice the minimum precision boolean This type represents a logical value true or false Char This type represents a single character and is described in Chapter8 Literals and Variables The simplest terms that appear in expressions are literals and variables The value of a literal does not change during course of a pro r 39 le is a placeholder for a value that can be updated as the program runs A variable in Java is most easily envisioned as a box capable of storing a value tal contains an int Each variable has the following attributes r A name which enables you to differentiate one variable from another 7 A type which Specifies what type ofvalue the variable can contain 7 A value which represents the current contents of the variable The name and type ofa variable are fixed The value changes whenever you assign a new value to the variable using Expressions in Java The heart of the AddZIntegers program from Chapter 2 is the line int total n1 112 that performs the actual addition The n1 n2 that appears to the right of the equal sign is an example of an expression which specifies the operations involved in the computation An expression in Java consists of terms joined together by operators Each term must be one of the following 7 A literal constant such a5314159265 orquothe11 worldquot 7 A variable name such as n1 n2 or total 7 A method call that returns a value such as eadInt 7 An expression enclosed in parentheses Summary of the Primitive Types A data type is defined by a set ofvalues called the domain and a set of operations owing table shows the data domains and common operations for all eight ofJava s primitive types Literals and Variables The format of a literal depends on its e e integer literals consist of a string of digits optionally preceded by a minus sign as in o 42 71 or 1000000 7 Floatingrpolnt literals include a decimal point as in 314159265 or 10 o Floatingpoint literals can also be expressed in scientific notation by adding the letter E and an exponent atter the digits ofthe number so that aaaiaea represents the number 5 646x 1039 r The two literals oftype boolean are true and false 7 character and string literals are discussed in detail in chapter 8 For the moment all you need to lmow is that a string literal consists of a sequence of characters enclosed in quotation marks such as quothello world and a char literal is enclosed in single quotes 3 Java Variable Identi ers I Names you make up for variables are called identifiers I Identi ers in Java conform to the following rules 7 A variable name must begin with alowercase letter or the underscore character 7 The remaining characters must be letters digits or underscores airstxact else lnlexface impel hnnlean extends long switch lrxeak false nati e syncinnnized iryte final new this case finally nnll thxrm catcn flaat package tist chaz fox pxivale txansient class gold pxnlecled lxlle canst if public txy cantinne irrrnlenents xeunn vairi default innaxt snaxt valatile ria instancear static while double int slxiclfp 7 Identi ers should make their purpose obvious to the reader 7 Identi ers should adhere to standard conventions Variable Declaration and Initialization I Declaration of a variable is the int total part of the statement below I Initialization of a primitive variable is the total 42 part int total 42 I Either of these parts can be a statement in iwelf although the declamtion must precede the initialization int total total 42 I Each name for a variable can be declared only once but the value stored in the name can be changed any number of times within a given set of curly braces Operators and Operands in most languages Java programs spe 39 of arithmetic exp ciiy n comp a o r closely resemble expressions in mathematics umeric essions that I The most common operators in Java are the ones that specify arithmetic computation Addition Multiplication Subtraction Division I Operators in Java usually appear between two subexpressions which are called its operands Operators that take two operands are called binary operators The opemtor can also appear as a unary operator as inthe expression x which denotes the negative of x Variable Declarations In Java you must declare a variable before you can use it The declaration establis es the name and e of the variable d in most cases speci es the initial value as well The most common form of a variable declaration is type name value where type is the name of a Java primitive type or class name is an identi er that indicates the name of the variable and value is an expression specifying the initial value Until we get to Ch 6 all variable declarations will appear as statements inside the curly braces of a method de nition These are called local variables and are accessible only inside that method Variable Declaration and Instantiation Declaration is also necessary when a variable is of object type h 39 1 T e declamtion ofGRect rectl is shown be ow Instantiation of an object variable requires using the new keyword and calling the class constructor GRect rectl new GRect1002005050 GRect rectl rect1 new GRect1002005050 Objects can also be declared before they are instantiated Division and Type Casts I Whenever you apply a binary operator to numeric values in Java the result will be of type int if both operands are of type int but will be a double if either operand is a double I This rule has important consequences in the case of division For example the expression 14 5 seems as if it should have the value 28 but because both operan s are of e int Java computes an integer result by throwing away the fractional part The result is therefore 2 I If you want to obtain the mathematically correct result you need to convert at least one operand to a double as in double 14 5 The conversion is accomplished by means of a type cast which consists ofa type name in parentheses The Pitfalls of Integer Division Consider the following Java statements which are intended to convert 100 Celsius temperature to its Fahrenheit equivalent 100 double c 95c32 double f The computation consists of evaluating the following expression The problem arises from the 1 3 2 fact that both 9 and 5 are type int The Remainder Operator The only arithmetic operator that has no direct mathematical counterpart is which applies only to integer operands and computes the remainder when the rst divides by the second 14 5 returns 4 14 7 returns 0 7 14 returns 7 The result of the operator make intuitive sense only if both operands are positive The examples in this book do not depend on knowing how works with negative numbers The remainder operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study Precedence If an expression contains more than one operator Java uses precedence rules to determine the order of evaluation The arithmetic operators have the following relative precedence highest unary type cast lowest Thus Java evaluates unary operators and type casts rst then the operators and and then the operators and Precedence applies only when two operands compete for the same operator If the operators are independent Java evaluates expressions from left to right Parentheses may be used to change the order of operations The Pitfalls of Integer Division You can x this problem by converting the fraction to a double either by inserting decimal points or by using a type cast double c 100 double f double 9 5 c 32 The computation now looks like this 2120 1800 18 90 doul e9 5 c 32 Exercise 1 Declare an integer variable number 2 Initialize number to have value 25 3 Describe how to use the operator to determine if number is even or odd Exercise Precedence Evaluation What is the value of the expression at the bottom of the screen 4 12345678910 Assignment Statements You can change the value of a variable in your program by using an assignment statement which has the general form variable expression The effect of an assignment statement is to compute Ie evaluate the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the le Thus the assignment statement total total value adds together the current values of the variables total and value and then stores that sum back in the variable total When you assign a new value to a variable the old value of that variable is lost Increment and Decrement Operators Another important shorthand form that appears frequently in Java programs i th inc ement ope t 39ch is most commonly written immediately alter a variable like 395 x The effect of this statement is to add one to the value of x which means that this statement is equivalent to x 1 or in an even longer form x x 1 The operator which is called the decrement operator is similar but subtracts one instead of adding one Boolean Operators The operators used with the boolean data type fall into two categories relational operators and logical operators I There are six relational operators that compare values of other types and produce a boolean result Equals Not equals lt Less than lt Less than or equal to gt Greater than gt Greater than or equal to For example the expression n lt 10 has the value true ifn is less than or equal to 10 and the value false otherwise I There are also three logical operators ampamp Logical AND p ampamp qmeans both p and q Logical 0R p q means either p or q or both Logical NOT p means the opposite ofp Shorthand Assignments I Statements such as total total value are so common that Java allows the following shorthand form total value I The general form ofa shorthand assignment is variable op expression where op is any of Java s binary operators The effect of this statement is the same as variable variable op expression For example the following statement multiplies salary by 2 salary 2 Boolean Expressions In many ways the most important primitive type in Java is boolean even though it is by far the simplest The only values in the boolean domain are true and false but these are exactly the values you need ifyou want your program to make decisions The name boolean comes from the English mathematician George Boole who in 1854 hi o t e Mathematzcal rlieoiies of Luglc aiiii Probabilities That 00k introduced asystem of logic that has come to be known as Boolean algebra which is the foundation for t eboolean atatype Gmrge Boole 179171871 Notes on the Boolean Operators I Remember that Java uses to denote assignment To test whether two values are equal you must use the operator anson as is o en done express the idea embodied in the mathematical expression 0 S x S 9 you need to make both comparisons explicit as in It is not legal in Java to use more than one relational operator in 39 e 39 39 in ma ematics To 0 lt x ampamp x lt 9 I The operator means either or both which is not always clear in the English interpretation of or I Be careful when you combine the operator with ampamp and I because the interpretation o en differs from informal English P Nt Equot 39 ShortCircuit Evaluation Java evaluates the ampamp and operators using a strategy called shortcircuit mode in Which it evaluates the right operand only ifit needs to do so For example ifn is 0 the right hand operand of ampamp in n 0 ampamp x 1 n is not evaluated at all because n 0 is false Because the expression false ampamp anything is always false the rest of the expression no longer matters One of the advantages of shortcircuit evaluation is that you can use ampamp and to prevent execution errors If n Were 0 in the earlier example evaluating x 1 n Would cause a division by zero error Review Name the 4 primitive data types We Will use in this class Declare a Whole number called numCars Initialize numCars value to 4 Declare a boolean called applianceOn and set it equal to false Declare and instantiate a GOval called outerRing a GOval constructor needs an x y coordinate a Width and a height Declare a GOval called innerRing Instantiate outerRing to be a circle with radius 50 positioned at the origin I While it is clearly necessary for you to Write program Designing for Readability s the compiler can understan good programmers are qually concerned with writing code that people can understand The importance of human readability arises from the fact that programs must be maintained over their life cycle Typically as much as 90 percent of the programming effort comes after the initial release ofa system Th e are several useful techniques that you can adopt to increase readability r u cplupcl plu lam Heal A The End Recursion Supplement CM PU1 O1 ProblemSolving and Abstraction Jennifer Walter Vassar College Fall 2008 The MTList Class The IList Union of Classes put it An Ilist is either empty or a construction consisting of the it first element and the rest of the list public interface IList p Interfaces can contain only method signatures and named constants All methods defined must be overridden in subclasses public int length public boolean containsint x publi an arenlloddo public int sunmll public int productnllo The ConsLis t Class public class MTList implements IList public mListo public int length return public boolean containsint x l public boolean arenlloddo public string tostring return quot0quot public int sumnllo Fill in the empty public int productmlo methods hint all are oneliners public class ConsList implements IList a s A list of ints contains a first element and a reference rest to sublists contained in this list it p 39vate int first private IList rest it Constructor needed to set instance variables In order to it create new ConsList need integer and existing ILis a public ConsListint first IList rest thisfirst f39 st thisrest res put it returns 1 plus the length of the rest of this list it public int length return thisrestlength l The ConsLis t Class p it returns true if x thisfirst or if x is in thisrest public boolean containsint x l p it returns true only iff all numbers in list are odd public boolean arenlloddo The ConsLis t Class put it returns sum of all integers in this ConsList a public int sumnllo it returns product of all integers in this ConsList public int productnllo a it returns string representation of this ConsList public string tostringo return quotquotthis firstquot quotthisresttoStringquot quot lList Methods that return lLists Write a method doubleList that returns a new lList that is the equivalent of the receiving lList but with each integer multiplied by 2 Write a method onlyEvens that returns a new lList containing only the even integers in the receiving lList lList Methods that return lLists Write a method called removeXint x to return a new lList excluding the rst occurrence of x assume the MTList version returns the empty list The TestIList Class t xiqinal 1is s a natmalsl i m m Systemnnlpxinllnt xepealLis xepeauaisl he xecuxsive mstha s on m lists a Systemnulpxl llnt n39l39eslinq xecmsive ms hnds i Systemnulpxinlln natualslenqlht should he 5 and is natualslenqlht Systemnulpxinllnt mtlenqth should he n and is Systemnulpxinllnt n naluxalsmnnlainstd shnuld he mllenqlh1 tins and is natmalscnntains14 Systemnnlpxinllnt natualscnnlain511 should he false and is naun scnntains 1D Systemnnlpxinllnt mt mtmnntainsuil shnuld he false and is cnntainsmn lList Methods that return lLists Write a method addToEndint X that is called on an lList and that returns a new lList with X appended to the end as the rightmost integer in the list Write a method called getlthint i to return the ith element of an lList assume the n elements of the list are indexed 0nl and that the MTList version prints quotno such elementquot after which I is returned The TestIList Class imynxt javaxswinqquot fnx J plinnl ane class public class nstmist l Standaha alu m tu i miss 39 ml1i static vnid mintstxinqn alas l A list of naunal numhexs fxmn tn 6 l mist natuaals new CnnsLisltE c n istt new mistmnm mist mt new MTList ellle list In A xepelilive list of numhexs mist xepealLisL s The TestIList Class cuats a new mist that cantains an he numhexs f ascending nxdex nuts tits new I t am 1 to n in cansList LnnyList xeplaces old tumist public static mist makmistrint up mist templaisl new MTList m tint i 39 lemyLisL n i gtltl i r new cansListritmListp xeunn lemyLisl cuats a new mist that cantains n lmhexs lead fxmn tits 521 public static lList xeadlaisltl mist LempLisl m MTList int n n while 11 Inleqexpazselnl tJ ptinnPane sthnyutDialnq mu Enlex an int 01 n ta quit m gt n LennyList m CnnsLisltntnanist xeunn LenIyLisl warren r zcts and Classes Tobeaxm lh r a give manta Jm mm m ma m CMPUlOl Computer Science I ProblemSolving and Abstraction Jennifer Walter adapted from slides by Eric Roberts Methods to Generate Random Values 39I L I 00 n4 Remms arandom color Defining Your Own Classes The standard form ofa class de nition in Java looks like this public class name extends rapeysiarr i class may The optional extends clause on the header line specifies the name of the superclass Ifthe extends clause is missing the new class becomes a direct subclass of object which is the root of Java s class hierarchy The body of a class consists ofa collection ofJava de nitions th calle entries 39 include s 39 named ally constructors method instance variables and nts Using the RandomGenerator Class The RandomGenerator class makes it possible to write progr s that simulate random processes such as ipping a coin or rolling a die Programs that involve random processes 0 this sort are said t be nondeterministjc Nondeterrninistic behavior is essential to many applications Computer games would cease to be fun if they behaved in exactly the same w each i e onde rrninism also has important practical uses in simulations in computer security and in algorithmic research Using the Random Methods If you have an instance variable of type RandomGenerator called rgen can use any of the methods shown on the previous slide using rgen as the receiver As an example you could simulate rolling a die by calling int 1e this gen nextInt 1 6 The 2parameter nextInt method returns a random integer with value 1 2 3 4 5 or 6 ie 1 through 6 This method call would return a number corresponding to one ofthe faces of a 6sided die Representing Student Information Understanding the structure of a class is easiest in the context of a specific example Suppose we want to create a class cal ed student which is used to keep track of the following information about a student 7 The name ofthe student 7 The studmt s slxrdlglt identi cation number The n mbar of credits the student has earned which may include a decimal actlon to account for half and quarterrcredlt courses 7 A boatean indicating whetherthe studenthas paid all university fees a h of these values is declared in an instance variable of the appropriate type Instance variables should always be declared as p vah Access to these values is controlled by public methods exported by the Studht Class To distinguish instance From local variables always use this when using an instance variable inside a method The Student Class 1111 comment dascvtbtz the 5111 d dwhole put it The student class keeps track of the following pieces of data it about a student the student39s name ID number the number of t has earned toward graduation and whether tr the student is paid up with respect to university bills cl ss in ormation only by using the various tr methods defined by the class publ c class student Milass hmdtzy de ne student aadmz tul7 1a of hect The S tudent Class quot zeparameter constructor tr Creates a new student object with the specified name and m tr n e The student39s name as a strin tr id The student39s ID number as an int a public name int id thissmdmmme name Note ha Illxtommtzmdzsrwbtzrhizmmrmrmv thisstudentID i vars zhe commlctor set the mrtzhee variable Melee mead an it Returns the number of credits earned by this student a public double getcreditso return thiscredits end method getcredits an tr sets whether the student is paid up tr flag The value true or false indicating paideup status a public void setPaid pboolean flag thispaidup flag end method setPaid p v gartth method mam a Returns whether the student is paid up a the we thlly begmr wfrh is public boolean islzaidupo return thispaidup end method isPailep M541 Hana Using the Student Class Once you have de ned the Student class you can then use is constructor to create instances of that class For example you could use the following code to declare and instantiate two S tudent obj ecw with Variable names shown student chosenone new StudentquotHarry Potterquot 123456 student topstudent new StudentquotHe11nione Grangerquot 314159 I You can then use the standard receiver syntax to call methods on these obj ects For example you could set Hermione s numberofcrediw eld to 97 by writing topstudent setcredits97 or get Harry s full name by calling chosenone getuameo put tr Returns the name of this student a public string getnameo return thisstudentuame end method get ame an it Returns the ID number of this student a public int getmo return thisstudentID end method getm zhere method Vary12W the valued eh mrtdhee varable dhd 0712 called gene s Became the swim hdme dhd ID numbav 0712 xed there IVE he eomerperdmgrettem 1hr method39ehdhger the vulva e dh mrtdhee Vartabltz andS edhed d rem put tr sets the number of credits e tr credits is the new numbe a public void setCredits double credits thiscredits credits end method setcredits arned r of credits earned M14 The S tudent it he Class put tr Creates a string identifying this stude tr Return the string used to display this a public string tostringo return thisstudentname w t m t A trn wquot nt student tnStxnuI method r of your glasses should own4142 tnStxllu Public constants quot The number of credits required for graduation public static final double CREDITS To cRnDunTE 340 Private instance variables private string studentllame The student39s name private int stud tID The student39s nu private double credits 0 number o credits earned private boolean paidup false Is student is paid u end class student zhere daclamnom de he39the mrtdhee Vartabltz that mdmtdm the mtemd cam4117142 rtdte ojthe clan A1 mmh hredm the textdre pvtva z were it an Exercise Design an Employee Class I Create a de nition for a class called Employee which keeps n tmck of the following lnformatlo e The name ofthe employee 7 A number indicating the order in which thi 5 employee we hired e A ag indicating whether the employee is still aetive e The salary a number that may contain a I The name and employee number shoul decimal fraction d be assigned as part of the constructor call and 1t should not be possible to change them subsequently By default ne w employees should be 39 d marked as active The salary eld need not be initiallze I The class should export appropriately named getters for all two four elds and setters for the last Rational Numbers As a more elaborate example of class de nition section 64 de nes a class called Rational that represents rational numbers which are simply the quotient of two integers Rational numbers can be useful in cases in which you need exact calculation with fractions Even if you use a double the oatingpoint number 01 is represented internally as an approximation The rational number 1 10 is exact Rational numbers support the standard arithmetic operations Addition Multiplication a c 7 adbc a c 7 ac i i i 7 i X i 7 7 b 0 bd b 0 bd Subtraction Division 7 i M a i L LG I 0 bd b d 175 Adding Three Rational Values public TestRational thisstart Rational a new Rational1 2 Rational b new Rational1 3 Rational c new Rational1 6 Rational sum aadd b addc printlnaquotquotbquotquotcquotquotsum a b c sum e g e Temaanonal 12 13 16 1 slap simulation The FilledRect Class This class is a GObject subclass that is almost identical to GRect except that it starts out filled instead of outlined public class FilledRect extends GRect Creates a new FilledRect with the specified bounds public FilledRectdouble x double y double width double height r s e t Fille d true This syntax Calls the superclass magnume Creates a new FilledRect with the specified bounds and color public FilledRectdouble x double double width double height Color color Simulating Rational Calculation The next slide works through all the steps in the calculation of a simple program that adds three rational numbers 1 l l 2 3 6 With rational arithmetic the computation is exact If you write this same program using variables of type double the result looks like this s s Hounumsxample 1020 1030 1060 0999999999999999 Extending Existing Classes Student Employee and Rational all extended the builtin obj ect class There are times when you want to extend an existing class to create a new class that inherits most of its behavior from its superclass but makes some small extensions or changes Suppose for example that you wanted to de ne a new class called FilledRect that is similar to the GRect class except that it is lled rather than outlined by default Moreover as a convenience you would like to be able to specify an optional color for the rectangle as part of the constructor Calling thisaddnew FilledRect10 10 100 75 ColorRED for example should create a 100x75 rectangle solidly lled in red and then add it to the canvas at the point 10 10 The code for the FilledRect class appears on the next slide Rules for Inherited Constructors Whenever you create an object of an extended class Java must call some constructor for the superclass object to ensure that its structure is correctly initialized If the superclass does not de ne any explicit constructors Java automatically provides a default zeroparameter constructor with an empty body following ways 7 Constructors that begin with an explicit call to this invoke one of the other constructors for this class delegating responsibility to that constructor for making sure that the superclass constructor gets called Java therefore invokes the superclass constructor in one of the e Constructors that begin with a call to super invoke the constructor in the superclass that matches the argument list provided 7 Constructors that begin with no call to either super or this invoke the default superclass constructor with no arguments Rules for Inherited Methods When one class extends another the subclass is allowed to override method de nitions in its superclass Whenever you invoke that method on an instance of the extended class Java chooses the new version of the method provided by that class and not the original version provided by the superclass The decision about which version of a method to use is always made on the basis of what the object in fact is and not on what it happens to be declared as at that point in the code The Role of Event Listeners One way to visualize the role of a listener is to imagine that you have access to one of Fred and George Weasley s Extendable Ears from the Harry Potter series 8 s 6 Lmeneraxample 3 A Simple Eventdriven Program The easiest way to illustrate event handling is by example The following program listens for mouse clicks and simulates the sun rising over the edge of the graphics window going higher with each click Raises a G val the sun public class Sunrise extends GraphicsProgram public GOval sun public Sunrise this start sun new GOvalthisgetWidth2 100 thisgetHeight 200200 sunsetFilledtrue sun setColor ColorYELLOW this addsun this addMouseListeners quot39 executed when mouse button is clicker public void mouseClickedMcuseEvent e sunmcve0 5 Writing Graphics Programs that Respond to Mouse Events Graphics applications often make it possible for the user to control the action of a program by using an input device such as a mouse Programs that support user control are called interactive programs aka Graphical User Interfaces or GUIs User actions such as clicking the mouse are called events Programs that respond to events are said to be eventdriven When you write an eventdriven program you indicate the events to which you wish to respond by adding a listener for that event When the event occurs a message is sent to the listener triggering a response Each response must be coded in a separate method with a particular signature and you must write the code in the body of each method Methods that Respond to Mouse Events To write a graphics program that responds to Mouse events you should include the line this addMouseListener in the constructor After including this line your program can include the following void methods to respond to mouse clicks mouse releases and other mouse events mous eclicked e Called when the user clicks the mouse mous ePressed e Called when the mouse button is pressed mouseReleased e Called when the mouse button is released mous eMoved e Called when the user moves the mouse mouseDragged e Called when the mouse is dragged with the button down A Simple Event driven Program When the user clicks the mouse Java responds by invoking the mouseClicked method in the listener The argument e is a MouseEvent object that describes the event Raises a GOval the sun public class Sunrise extends GraphicsProgram public GOval sun public Sunrise this start sun new GOvalthisgetWidth2 100 this getHeight 200 200 sunsetFilled true sun setColor ColorYELLOW thisaddsun this addMouseListeners l executed when mouse hutth is clicked public void mouseClickedMouseEvent e sunmove 0 5 A Simple Eventdriven Program Graphics Interlude The definitions for the standard event and listener classes are in the javaawtevent package which means that you need to import this package in interactive programs Using images in your programs Suppose we want to do more than just draw our own objects in a GraphicsProgram It is very simple to insert digitized images into your programs Raises a 601131 the sun public class Sunrise extends GraphicsProgram pE c Seven s1u1 The GImage class is used to constuct images on the canvas p 1C unrise 39 39 thisstart 0 Suppose I had the followrng image that I wanted to place on sun new Govalthisgetwidth2 10 the canvas 0 thisgetHeight 200200 sun setFilledtrue sun setColor Color YELLOW this add sun this addMouseListeners executed when mouse button is clicked public void mouseClickedMouseEvent e sunmove05 l Using the GImage class The GImage class 0 Use the following lines to declare and add the GImage shown Files that can be used as images have either a jpg or gif on the last slide called quotHappySunjpgquot to a graphics eXtenswn program The image file should be in the same directory ie folder as any Java program that uses the image private GImage sun Methods that can be called on a GImage can be found in the sun 2 new GImage Happysun 39 3 pg 10 O 100 acm library documentation ie the ACM Java API The SunriseImage Class The SunriseImage Class import acmprogram 0 parameter constructor import acmgraphics I ll1 11C SunriseImageO import javaawtevent thisStartOF Create sun in its initial osition P This class raises a cool sun as the mouse is clicked thissun new GImageuHappy5unjpgu thissunsetBoundsthisgetWidth2 SUNSIZE2 public class SunriseImage extends GraphicsProgram thisgetHeight I SUN SIZE SUN SIZE thisaddsun instance variable for sun P111311C 51111399 51111 Add the mouse listener this addMouseListeners named constant for diameter of sun public static final int SU39NSIZE 400 named COHStant for mOVe inCrementS Each mouse click causes the GImage sun to move up Public Static final int MOVEU39P 10 public void mouseClickedMouseEvent e sunmove 0MOVEU39P l page 1 12 page 2 112


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.