Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition makes solving textbook exercises easier with step-by-step solutions and helpful tips.

Hannah Perez
Contributor
4.5
50
5 months ago
Preview (16 of 126 Pages)
100%
Purchase to unlock

Page 1

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 1 preview image

Loading page image...

Exercise 1.3Use a negative parameter value to move left, e.g.-70Exercise 1.9The House PictureThe main building:Create a new Square objectInvoke its method makeVisible()Make the square bigger by invoking the method changeSize(newSize) (100is a good size)Move the square down by invoking the method moveVertical(distance)(again 80 is a good value)The window:Create a new Square object.Invoke its method makeVisible()Change its color by invoking changeColor()write "black" in the popupwindowMove the square down by invoking the method moveVertical(distance)(100 is a good value)Move it to the right by invoking moveRight()The roof:Create a new triangle object.Invoke its method makeVisible()Change its size with changeSize(newHeight, newWidth) (50,140)moveVertical(70)moveHoizontal(60)The sun:Create new Circle object.Invoke its method makeVisible()Change its color by invoking changeColor() (write "yellow" in the popupwindow) Optionally change its size with changeSize(60)Move it to the right by invoking moveHorizontal(180)The Hilltop PictureThe hill:

Page 2

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 2 preview image

Loading page image...

Page 3

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 3 preview image

Loading page image...

Create a new Circle object.Invoke its makeVisible() method.Change its color by invoking changeColor (write “green” in the popupwindow) Change its size with changeSize to something like 1000.Move it left with moveHorizontal(-500).Move it down with moveVertical(125).The sun:Create a Circle.Make it visible.Set its size to 30.Move it right by 150 pixels.Move it down by 50 pixels.The larger figure:Create a new Person object.Invoke its makeVisible method.Change its size to something like 50 high and 25 wide.Move it left by 30 pixels and up by around 8.The smaller figure:The size should be around 40 by 20.Move it left by 3 pixels and down by 2.Exercise 1.14It uses the objects of the classes Circle, Square and Triangle.It then moves these objects to the right places and changes the sizes andcolors of the objects. Essentially calling the same methods as used inexercise 1.9Exercise 1.16Change:sun.changeColor("yellow");to be:sun.changeColor("blue");Note that this change should be made in both the draw() and setColor() methods.Students often forget to do it in the latter. Illustrate the problem by drawing the

Page 4

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 4 preview image

Loading page image...

picture, then calling setBlackAndWhite() then setColor() – the sun will have beenchanged to yellow, rather than blue, if the second change is not made.Exercise 1.17The second sun will need to be positioned somewhere different from the first sunto be visible. As with the previous exercise, it is common for students to miss theneed to change the setColor and setBlackAndWhite methods for compatibility withthe addition. This is an earlier introduction to the need forregression testing!Exercise 1.18After the line sun.makeVisible() insert the following:sun.slowMoveVertical(250);Compile the Picture class (Press compile in the editor window)Create instance of class Picture and invoke its draw() method.Exercise 1.19Remove the line (if added in the previous exercise): slowMoveVertical(250); Rightbelow the last } after the draw() method, add the sunset() method :/***Animatesthesunset.*/publicvoidsunset(){sun.slowMoveVertical(250);}Compile! And run it.Exercise 1.20Define a new field:privatePersonperson;Initialize and position them in the draw():person=newPerson();person.changeSize(80,40);//Placethematgroundlevel.person.moveVertical(15);//Makesuretheyaretotherightofthehousetostart.person.moveHorizontal(200);Make them visible and move up to the house in sunset():person.makeVisible();//Walkuptothehouse.person.slowMoveHorizontal(-150);

Page 5

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 5 preview image

Loading page image...

Exercise 1.22When calling the method getName(), the name of the student is displayed in apopup window. The name displayed is the one typed in when the object wascreated.Exercise 1.24It shows the number of students in the LabClass which is zero.Exercise 1.31Students looking these values up in the tutorial might not be able to readilyidentify that the integer types used here are int, as opposed to byte, short or long.Similarly, they may well suggest float rather than double for the final one. Be sureto point out that String always has an initial upper-case letter, because thesesubtleties are often missed.0int"hello"String101int-1inttrueboolean"33"String3.1415doubleExercise 1.32First you would have to decide which type the field should have. String would be agood type to hold a name, so we add the following line to the source file of Circle:privateStringname;The above line could be placed after this line in the source code of the Circle class:privatebooleanisVisible;Exercise 1.33publicvoidsend(Stringmsg)The name msg is arbitrarily chosen.Exercise 1.34publicintaverage(intfirstNumber,intsecondNumber)Exercise 1.35The book is an object because it isa specific instanceof the Book class.

Page 6

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 6 preview image

Loading page image...

Exercise 1.36Yes, an object can belong to several classes. One of the more famous examples isthe platypus, which is both a mammal and egg-laying.

Page 7

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 7 preview image

Loading page image...

Exercise 2.2Zero.Exercise 2.3If too much money is inserted the machine takes it all - no refund.If there isn't enough money inserted, it still prints out the ticket.Exercise 2.5It looks almost completely the same. Only the price on the ticket is different.Exercise 2.6The outer part of the student class:publicclassStudent{}The outer part of the LabClass class:publicclassLabClass{}Exercise 2.7Yes, the order of public and class matters.Exercise 2.8It is possible to leave out the wordpublic.Exercise 2.9It is not possible to leave out the wordclass.Exercise 2.10Fields:pricebalancetotalConstructors:TicketMachine

Page 8

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 8 preview image

Loading page image...

Methods:getPricegetBalanceinsertMoneyprintTicketExercise 2.11It does not have any return type. The name of the constructor is the same as thename of the class.Exercise 2.12intStudentServerExercise 2.13alivetutorgameExercise 2.14Student,Server,PersonandGameExercise 2.15The exact order matters.Exercise 2.16Yes, it always necessary to have a semicolon after a field declaration.Exercise 2.17privateintstatus;Exercise 2.18It belongs to the class Student.Exercise 2.19It has two parameters. One is of type String and the other of type double.Exercise 2.20It would be reasonable to expect the types to be the same as the two parameters(String and double).

Page 9

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 9 preview image

Loading page image...

Can't really assume anything about the names, but probably something like titleand price.Exercise 2.21name=petsName;Exercise 2.22publicDate(Stringmonth,intday,intyear)Exercise 2.23Aside from their names, the only difference is that getPrice() returns the value ofthe price field whereas getBalance() returns the value of the balance field.Exercise 2.24How much money have I inserted into the machine?Exercise 2.25No. There is no direct link between the name of a method and the name of thefield. However, it is a convention to use a name for the method that clearly links itto the field.Exercise 2.26publicintgetTotal(){returntotal;}Exercise 2.27Missing return statement.Exercise 2.28The header for getPrice() has an int as return type.The header for printTicket() has void as return type.Exercise 2.29No.Because they don't need to return anything.Yes. Both headers have void as return types.Exercise 2.31It has a return type (void) and constructors do not have return types. It also doesnot have the same name as the class it is in.

Page 10

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 10 preview image

Loading page image...

Exercise 2.32price=cost;Exercise 2.33score=score+points;Exercise 2.34It is a mutator.Use an inspector to view the current score, then call theincreasemethod with apositive parameter value and observe thatscoreincreases by that value.Alternatively, ifscorehas an accessor method; call the accessor, then callincrease, and then call the accessor once again to verify that it returns theupdated value, indicating that the field has been modified.Exercise 2.35price=price-amount;Exercise 2.36Note that no quote marks are printed, just the following:Mycathasgreeneyes.Exercise 2.37publicvoidprompt(){System.out.println("Pleaseinsertthecorrectamountofmoney.");}Exercise 2.38Instead of printing out the actual price of the ticket, it displays the word "price":#pricecents.Exercise 2.39Prints out the exact same string as in exercise 2.38Exercise 2.40No, because neither uses the value of the price field in the println statement.Exercise 2.41publicvoidshowPrice(){System.out.println("Thepriceofaticketis"+price+"cents.");

Page 11

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 11 preview image

Loading page image...

}Exercise 2.42They display different prices. This is because each ticket machine object has itsown price field.The price that was set in one ticket machine does not affect the other ticketmachine’s price.The unique value of each ticket machine's price field is substituted into the printlnstatement whenthe method is called.Exercise 2.43publicTicketMachine(){price=1000;balance=0;total=0;}When constructing a TicketMaching object you will not be prompted for aparameter value.The tickets always have a price of 1000 cents.Exercise 2.44publicTicketMachine(){price=1000;balance=0;total=0;}publicTicketMachine(intticketCost){price=ticketCost;balance=0;total=0;}Exercise 2.45publicvoidempty(){total=0;}It needs no parameters.It is a mutator.Exercise 2.46The balance does not change when an error message is printed.Inserting zero results in an error message.Exercise 2.47

Page 12

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 12 preview image

Loading page image...

This version does not print an error message when zero is inserted.Other than that, it does not change the observable behavior of the method.Exercise 2.48Note the importance of using<=rather than<in the rewritten condition.if(amount<=0){System.out.println("Useapositiveamountratherthan:"+amount);}else{balance=balance+amount;}Exercise 2.49The field is: isVisible.It determines whether the circle was visible or not.Yes. As a circle is either visible or not, only two states (values) are needed.Exercise 2.50In the printTicket method of Code 2.8 the total is increased only by the price of theticket, and not the full balance.The balance is then decreased by the price.Exercise 2.51The else and associated block can be removed – if statements do not have to havean else part.If an illegal amount is used, no error message is printed but the method otherwiseworks correctly.Exercise 2.52It could never become negative. The value in balance is checked in printTicket toensure that it is always at least as large as price, so when price is subtractedbalance cannot become negative.Exercise 2.54saving=price*discount;Exercise 2.55mean=total/count;Exercise 2.56if(price>budget){System.out.println("Tooexpensive.");}else{System.out.println("Justright.");}Exercise 2.57

Page 13

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 13 preview image

Loading page image...

if(price>budget){System.out.println("Tooexpensive.Yourbudgetisonly:"+budget);}else{System.out.println("Justright.");}Exercise 2.58Because balance is set to zero and then this new value is returned rather than theold one. The method will always return zero. It can be tested by inserting anamount, and then calling refundBalance(). The original would then return theamount inserted, but the new method returns 0.Exercise 2.59An error is printed: unreachable statement.A return statement ends (exits) the method. Code after a return statement cantherefore never be executed.Exercise 2.60The variable price is being re-declared as a local variable in the constructor – thisis the effect of the word int in front of it. This local variable ‘hides’ the field of thesame name. So the ticket price is never assigned to the price field.Exercise 2.61publicintemptyMachine(){intoldTotal=total;total=0;returnoldTotal;}Exercise 2.62publicvoidprintTicket(){intamountLeftToPay=price-balance;if(amountLeftToPay<=0){//Simulatetheprintingofaticket.System.out.println("##################");System.out.println("#TheBlueJLine");System.out.println("#Ticket");System.out.println("#"+price+"cents.");System.out.println("##################");System.out.println();//Updatethetotalcollectedwiththeprice.total+=price;//Reducethebalancebytheprince.balance-=price;}else{System.out.println("Youmustinsertatleast:"+amountLeftToPay+"morecents.");}

Page 14

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 14 preview image

Loading page image...

}Exercise 2.63You would need fields to store the prices of each of the tickets that the machinecan issue.You would need a method to select which type of ticket you would want.It will not be necessary to modify many of the existing methods, if the price field isupdated each time you select a new ticket type. You would probably need tomodify the constructor, to allow several ticket prices.Exercise 2.64Name: getCodeReturn type: StringExercise 2.65Name: setCreditsParameter name: creditValueParameter type: intExercise 2.66publicclassPerson{}Exercise 2.67privateStringname;privateintage;privateStringcode;privateintcredits;Exercise 2.68publicModule(StringmoduleCode){code=moduleCode;}Exercise 2.69publicPerson(StringmyName,intmyAge){name=myName;age=myAge;}Exercise 2.70

Page 15

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 15 preview image

Loading page image...

The return type should not be void.publicintgetAge(){returnage;}Exercise 2.71publicStringgetName(){returnname;}Exercise 2.72publicvoidsetAge(intnewAge){age=newAge;}Exercise 2.73publicvoidprintDetails(){System.out.println("Thenameofthispersonis"+name);}Exercise 2.74student1 : Studentname: Benjamin Jonsonid: 738321credits: 0Exercise 2.75"Henr557"Exercise 2.76It opens the editor with the source code for the Student class. It displays amessage: StringIndexOutOfBoundsExceptionThis happens because the method getLoginName expects the name to be at least 4characters long and "djb" is only 3 characters.Exercise 2.77publicStudent(StringfullName,StringstudentID){if(fullName.length()<4){System.out.println("Error!Thenameshouldbeatleast4characterslong");}if(studentID.length()<3){

Page 16

Solution Manual for Objects First with Java: A Practical Introduction Using BlueJ, 6th Edition - Page 16 preview image

Loading page image...

System.out.println("Error!ThestudentIDshouldbeatleast3characterslong");}name=fullName;id=studentID;credits=0;}Exercise 2.78publicStringgetLoginName(){StringloginNamePart;if(name.length()<4){loginNamePart=name;}else{loginNamePart=name.substring(0,4);}StringloginIdPart;if(id.length()<3){loginIdPart=id;}else{loginIdPart=id.substring(0,3);}returnloginNamePart+loginIdPart;}Exercise 2.79102"catfish""cat9""12cat""cat39""f"StringIndexOutOfBoundsExceptionExercise 2.80The first call returns 0 and the second returns 500.Exercise 2.81Because t2 refers to the same object as t1, the call will print 500.This example ofaliasingis an important one and students should try to ensure thatthey understand what is going on here.Exercise 2.82The call returns 1000. Even though the change was made via t1, because t2 isreferring to the same object, it sees the new value. Note that we have only createda single TicketMachine object in these two exercises, but two variables refer tothat one object.Exercise 2.83
Preview Mode

This document has 126 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all