2.1 | Create a TicketMachine object on the object bench and take a look at its methods. You should see the following: getBalance(), getPrice(), insertMoney(), and printTicket(). Try out the getPrice() method. You should see a return value containing the price of the tickets that was set when this object was created. Use the insertMoney() method to simulate inserting an amount of money into the machine and then use getBalance() to check that the machine has a record of the amount inserted. You can insert several separate amounts of money into the machine, just like you might insert muliple coins or notes into a real machine. Try inserting the exact amount required for a ticket. As this is a simple machine, a ticket will not be issued automatically, so once you have inserted enough money, call the printTicket() method. A facsimile ticket should be printed in the BlueJ terminal window. | Done. |
2.2 | What value is returned if you check the machine's balance after it has printed a ticket? | 0. |
2.3 | Experiment with inserting different amounts of money before printing tickets. Do you notice anything strange about the machine's behavior? What happens if you insert too much money into the machine - do you receive any refund? What happens if you do not insert enough and then try to print a ticket? | It prints out a ticket. |
2.4 | Try to obtain a good understanding of a ticket machine's behavior by interacting with it on the object bench before we start looking at how the TicketMachine class is implemented in the next section. | Done. |
2.5 | Create another ticket machine for tickets of a different price. Buy a ticket from that machine. Does the printed ticket look different? | Yes, the amount of money on the ticket changes. |
2.6 | Write out what you think the outer layers of the Student and LabClass classes might look like - do not worry about the inner part. | public class Student {} public class LabClass {} |
2.7 | Does it matter whether we write public class TicketMachine or class public TicketMachine in the outer wrapper of a class? Edit the source of the TicketMachine class to make the change and then close the editor window. Do you notice a change in the class diagram? What error message do you get when you now press the compile button? Do you think this message clearly explains what is wrong? | Yes, it matters. I get the message "expected". I don't think it's that clear. |
2.8 | Check whether or not it is possible to leave out the word public from the outer wrapper of the TicketMachine class. | Yes. |
2.9 | From your earlier experimentation with the ticket machine objects within BlueJ you can probably remember the names of some of the methods - printTicket() for instance. Look at the class definition in code 2.1 and use this knowledge, along with additional information about ordering we have given you, to try to make a list of the names of thefields, constructors, and methods in theTicketMachine class. Hint: There is only one constructor in the class. | Fields: price, balance, total Constructors: TicketMachine Methods: getPrice, getBalance, insertMoney, printTicket |
2.10 | Do you notice any features of the constructor that makes it significantly different from the other methods of the class? | It creates the whole machine. It doesn't just do an action, it basically creates the program. |
2.11 | What do you think is the type of each of the following fields? private int count private Student representative private Server host | The first one is an integer, the second one is a type of Student and the third one of type Server. |
2.12 | What are the names of the following fields? private boolean alive private Person tutor private Server host | Alive, tutor and host. |
2.13 | In the following declaration from theTicketMachine class private int price; does it matter which order the three words appear in ? Edit the TicketMachine class to try different orderings. After each change, close the editor. Does the appearance of the class diagram after each change give you a clue as to whether or not the other orderings are possible? Check by pressing on the compile button to see if there is an error message. Make sure that you reinstate the original version after your experiments. | There is a red question mark when a change isn't possible. |
2.14 | Is it always necessary to have a semicolon at the end of a field declaration? Once again experiment via the editor. The rule you will learn here is important, be sure to remember it. | Yes, it is. |
2.15 | Write in the full declaration for a field of typeint whose name is status. | private int status; |
2.16 | To what class does the followingconstructor belong? public Student (String name) | Class Student. |
2.17 | How many parameters does the followingconstructor have and what are their types? public Book(String title, double price) | It has two parameters. Their types are a string and a double. |
2.18 | Can you guess what types some of the Book class's fields might be? Can you assume anything about the names of its fields? | Probably price, name maybe something like that. It would be a string and a double. |
2.19 | Supose that the class Pet has a field called name that is of type String. Write an assignment in the body of the followingconstructor so that the name field will be initialized with the value of the constructor's parameter. public Pet (String petsName) { ...; } | name = petsName; |
2.20 | What is wrong with the following constructor of TicketMachine? public TicketMachine (int ticketCost) { int price = ticketCost; balance = 0; total = 0; } Once you have spotted the problem, try out this version in the naive-ticket-machineproject. Does this version compile? Create an object, and then inspect itsfields. Do you notice something wrong about the value of the price fiield in the inspector with this version? Can you explain why this is? | It states the type of field. You dont have to put the field at the beginning. Yes, it complies. The value of the price field in the inspector is 0. That's because when you put "int" in front of price, it creates a new variable that is different from the field price. |
2.21 | Compare the getBalance() method with thegetPrice() method. What are the differences between them? | They're the same except the getBalance() method returns the balance and the getPrice() method returns the price. |
2.22 | If a call to getPrice() can be characterized as "What do tickets cost?", how would you characterize a call to getBalance()? | What is the balance of the ticket machine? |
2.23 | If the name of getBalance() is changed togetAmount(), does the return statement in the body of the method need to be changed too? Try it out within BlueJ. | No. |
2.24 | Define an accessor method, getTotal(), thatreturns the value of the total field. | public int getTotal() { return total; } |
2.25 | Try removing the return statement from the body of getPrice(). What error message do you get when you try compiling the class? | It says "missing return statement" . |
2.26 | Compare the method signatures ofgetPrice() and printTicket() in code 2.1. Apart from their names, what is the main difference between them? | getPrice() has a return statement while printTicket() doesn't (but it does print a ticket). |
2.27 | Do the insertMoney and printTicketmethods have return statements? Why do you think this might be? Do you notice anything bout their headers that might suggest why they do not require return statements? | |
2.29 | How can we tell from just its header thatsetPrice() is a method and not aconstructor? public void setPrice(int ticketCost) | 27: No, they don't. They don't need them. It says void meaning no return value. 28. Done it. 29: It has a return type. |
2.30 | Complete the body of the setPrice() method so that it assigns the value of itsparameter to the price field. | price = ticketCost; |
2.31 | Complete the body of the following method, whose purpose is to add the value of itsparameter to a field named score. public void increase (int points) | score = score + points; |
2.32 | Can you compile the following method, whose purpose is to subtract the value of itsparameter from a field named price? public void discount (int amount) | price = price - amount; |
2.33 | Add a method called prompt() to theTicketMachine class. This should have avoid return type and take no parameters. The body of the method should print something like: "Please insert the correct amount of money." | Done. |
2.34 | Add a showPrice() method to theTicketMachine class. This should have avoid return type and take no parameters. The body of the method should print something like: "The price of a ticket is xyz cents" where xyz should be replaced by the valueheld in the price field when the method is called. | Done. |
2.35 | Create two ticket machines with differently priced tickets. Do calls to their showPrice() methods show the same output or different? How do you explain this effect? | Different. It's different because we put in a field and not a string number. |
2.36 | What do you think would be printed if you altered the fourth statement of printTicket()so that the price also has quotes around it as follows? System.out.println("# " + "price" + " cents."); | It would print the word price, literally. |
2.37 | What about the following version? System.out.println ("# price cents."); | It would print exactly "# price cents. " It always prints everything that's in quotation marks exactly as you wrote it. |
2.38 | Could either of the previous two versions be used to show the price of tickets in different ticket machines? Explain your answer. | No, because they wouldn't show the value stored in the variable. |
2.39 | Modify the constructor of TicketMachineso that it no longer has a parameter. Instead, the price of tickets should be fixed at 1000 cents. What effect does this have when youconstruct ticket machine objects within BlueJ. | It doesn't ask you for a price because it was already set in the method. |
2.40 | Implement a method, empty(), that simulates the effect of removing all money from the machine. This method should have a void return type, and its body should simply set the total field to zero. Does this method need to take anyparameters? Test your method by creating a machine, inserting some money, printing some tickets, checking the total then emptying the machine. Is this method a mutator or an accessor? | It doesn't need to take any parameters. It's a mutator. |
2.41 | Implement a method setPrice(), that is able to set the price of tickets to a new value. The new price is passed in as aparameter value to the method. Test your method by creating a machine, showing the price of tickets, changing the price, and then showing the new price. Is this method a mutator? Explain. | Yes, it's a mutator because it changes the value of variable price. |
2.42 | Give the class two constructors. One should take a single parameter that specifies the price, and the other should take no parameter and set the price to adefault value of your choosing. Test your implementation by creating machines via the two different constuctors. | Done it. |
2.43 | Check that the behavior we have discussed here is accurate by creating a TicketMachine instance and calling insertMoney() with various actual parameter values. Check the balance both before and aftercalling insertMoney(). Does the balance ever change in the cases when an error message is printed? Try to predict what will happen if you enter the value zero as the parameter, and then see if you are right. | Done it. |
2.44 | Predict what you think will happen if you change the test in insertMoney() to use thegreater-than or equal-to operator. if (amount>=0) Check your predictions by running some tests. What difference does it make to the behavior of the method? | It accepts 0. |
2.45 | In the shapes project we looked at in chapter 1 we used a boolean field to control a feature of the circle objects. What was that feature? Was it well suited to being controlled by atype with only two different values? | It was the field isVisible. It controlled whether the circle was visible or not. It was well suited. |
2.46 | In this version of printTicket() we also do something slightly different with the totaland balance fields. Compare the implementation of the method in Code 2.1 with that in code 2.8 to see whether you can tell what those differences are. Then check your understanding by experimenting within BlueJ. | In the second machine, a conditional statement was added and instead of clearing the balance, the balance was reduced by the price in order to return the money. |
2.47 | After a ticket has been printed, could the value in the balance field ever be set to a negative value by subtracting price from it? Justify your answer. | No, because the machine wouldn't let the ticket to be printed if less money than the price would be inserted. |
2.48 | So far we have introduced you to two arithmetic operators, + and -, that can be used in arithmetic expressions in Java. Take a look at Appendix D to find out what other operators are available. | There is *, / and %. |
2.49 | Write an assignment statement that will store the result of multiplying two variables,price and discount, into a third variable,saving. | saving = price*discount |
2.50 | Write an assignment statement that will divide the value in total by the value incount and store the result in mean. | mean = total/count |
2.51 | Write an if statementthat will compare thevalue in priceagainst the value inbudget. If price is greater than budget then print the message.. "too expensive" otherwise print the message.. "just right". | public void tooBuyorNottoBuy() { if(price>budget) System.out.printIn(“Too Expensive”); else return System.out.printIn(“Just Right”); } | ||||
2.52 | Modify your answer to the previous exercise so that the message if the price is too high includes the value of your budget. | public void tooBuyorNottoBuy() { if(price>budget) System.out.printIn(“Too Expensive, Current Budget:” + budget); else return System.out.printIn(“Just Right”); } | ||||
2.53 | Why does the following version ofrefundBalance() not give the same results as the original? public int refundBalance() { balance = 0; return balance; } What tests can you run to demonstrate that it does not? | This refundBalance() method simply clears balance, and returns it after after being cleared, meaning it’s value will always be returned as 0. You can try changing the method to this, creating an instance, calling the insertMoney() method, and then calling the returnBalance() method in order to check this. | ||||
2.54 | What happens if you try to compile theTicketMachineclass with the following version ofrefundBalance(): public int refundBalance() { return balance; balance = 0; } What do you know about return statements that helps to explain why this version does not compile? | It won’t compile because methods that return values always have to have the return block at the end of the method. | ||||
2.55 | Add a new method, emptyMachine(), that is designed to simulate emptying the machine of money. It shouldreturn the value intotal AND reset totalto be zero. | Done. | ||||
2.56 | Is emptyMachine() an accessor, amutator, or both? | It is a mutator because it changes the state of the object, and doesn’t return a message, rather it returns a printed message, which is different. Furthermore, it doesn’t tell us about the object, we just programmed the print message to say something that does. | ||||
2.57 | Rewrite the printTicket() methodso that it declares alocal variableamountLeftToPay. This should then beinitialized to contain the difference between price andbalance. Rewrite the test in the conditional statement to check the value ofamountLeftToPay. If its value is less than or equal to zero, a ticket should be printed, otherwise an error message should be printed stating the amount still required. Test your version to ensure that it behaves in exactly the same way as the original version. | Done. | ||||
2.59 | Draw a picture of the form shown in 2.3 representing the initial state of a Studentobject following its construction with the following actual parameter values: new Student ( "Benjamin Jonson", "738321") | Name: Benjamin Jonson ID: 738321 login name: Benj738 | ||||
2.60 | What would be returned by getLoginName() for a student with the name "Henry Moore" and the id "557214"? | Henr557 | ||||
2.61 | Create a student with the name "djb" and id "859012". What happens when getLoginName() iscalled on this student? Why do you think this is? | An error (String index out of range: 4). That's because the name is only long 3 characters and the method needs 4 characters. | ||||
2.62 | The String class defines a length()accessor method with the followingsignature: public int length() Add conditional statements to theconstructor of Student to print an error message if either the length of the fullNameparameter is less than 4 characters or the length of the studentId parameter is less than 3 characters. However the constructor should still use those parameters to set thename and id fields, even if the error message is printed. Hint: use if statements of the following form (that is, having no else part) to print the error messages. if (perform a test on one of the parameters) Print an error message if the test returns true | Done | ||||
2.63 | Modify the getLoginName() method ofStudent so that it always generates a login name, even if either of the name and idfields is not long enough. For strings shorter than the required length, use the whole string. | Done | ||||
2.64 | | Done | ||||
2.65 | Add two methods, printAuthor() andprintTitle(), to the outline Book class. These should print the author and title fields respectively, to the terminal window. | Done | ||||
2.66 | Add a further field, pages, to the Book class to store the number of pages. This should be of type int, and its initial value should bepassed to the single constructor, along with the author and title strings. Include an appropriate getPages() accessor method for this field. | Done | ||||
2.67 | Add a method, printDetails(), to the Bookclass. This should print details of theauthor, title and pages, to the terminal window. It is your choice how these details are formatted. For instance, all three items could be printed on a single line, or each could be printed on a separate line. You might also choose to include some explanatory text to help a user work out which is the author and which is the title. | Done | ||||
2.68 | Add a further field, refNumber, to the class. This field can store a reference number for a library, for example. It should be of type String and initialized to the zero length string("") in the constructor as its initial valueis not passed in a parameter to theconstructor. Instead, define a mutator for it with the following signature: public void setRefNumber (String ref) The body of this method should assign the value of the parameter to the refNumber field. Add a corresponding getRefNumber()accessor to help you check that the mutatorworks correctly. | Done | ||||
2.69 | Modify your printDetails() method to include printing the reference number. However, the method should print the reference number only if it has been set - that is, the refNumber string has a non-zero length. If it has not been set, then print the string "zzz" instead. Hint: Use a conditional statement whose test calls the length() method on therefNumber string. | Done | ||||
2.70 | Modify your setRefNumber() mutator so that it sets the refNumber field only if the parameter is a string of at least three characters. If it is less than three, then print an error message and leave the field unchanged. | Done | ||||
2.71 | Add a further integer field, borrowed, to theBook class. This keeps a record of the number of times a book has been borrowed. Add a mutator, borrow(), to the class. This should update the field by one each time it iscalled. Include an accessor getBorrowed(), thatreturns the value of this new field as its result. Modify printDetails() so that it includes the value of this field with an explanatory piece of text. | Done | ||||
2.72 | Create a new project, heater exercise, within BlueJ. Edit the details int the project description - the text note you see in the diagram. Create a class, Heater, that contains a single integer field, temperature. Define aconstructor that takes no parameters. Thetemperature field should be set to the value 15 in the constructor. Define the mutators warmer() and cooler(),whose effect is to increase or decrease the value of temperature by 5 degrees respectively. Define an accessor to return the value oftemperature. | Done | ||||
2.73 | Modify your Heater class to define three new integer fields: min, max andincrement. The values of min and maxshould be set by parameters passed to theconstructor. The value of increment should be set to 5 in the constructor. Modify the definitions of warmer() andcooler() so that they use the value ofincrement rather than the explicit value of 5. Before proceeding with this exercise check that everything works as before. Now modify the warmer() method so that it will not allow a temperature to be set that is greater than max. Similarly modify cooler()so that a temperature of less than mincannot be set. Check that the class works properly. Now add a method, setIncrement(), that takes a single integer parameter and uses it to set the value of increment. Once again, test that the class works as you would expect, by creating instances ofHeater in BlueJ. Do things still work as expected if a negative value is passed to thesetIncrement() method? Add a check to this method to prevent a negative value from being assigned toincrement. | Done but i also modified the increment to not be negative value | ||||
2.74 | You have now seen some examples of class, whose objects simulate the behavior of real world objects. In this exercise you should think of a different real-world object and design a class to simulate its behavior. | DONE :D | ||||
No comments:
Post a Comment