Main Menu

Showing posts with label exercises. Show all posts
Showing posts with label exercises. Show all posts

Thursday, May 8, 2014

Objects first with Java chapter 2 part 2


Exercise 2.62 Rewrite the printTicket method so that it declares a local variable, amountLeftToPay. This should then be initialized to contain the difference between price and balance. Rewrite the test in the conditional statement to check the value of amountLeftToPay. 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 left to pay. Test your version to ensure that it behaves in exactly the same way as the original version. Make sure that you call the method more than once, when the machine is in different states, so that both parts of the conditional statement will be executed on separate occasions.
public void printTicket()
{
    int amountLeftToPay = price - balance;
    if (amountLeftToPay <= 0) {        
         System.out.println("##################");
         System.out.println("# The BlueJ Line");
         System.out.println("# Ticket");
         System.out.println("# " + price + " cents.");
         System.out.println("##################");
         System.out.println();
}
else {
     System.out.println("Error while printing ticket " + amountLeftToPay);
}
}

Original Version:
public void printTicket()
{
if(balance >= price) {

        // Simulate the printing of a ticket.
        System.out.println("##################");
        System.out.println("# The BlueJ Line");
        System.out.println("# Ticket");
        System.out.println("# " + price + " cents.");
        System.out.println("##################");
        System.out.println();
 // Update the total collected with the price.
        total = total + price;
// Reduce the balance by the prince.
        balance = balance - price;
}
else {
         System.out.println("You must insert at least: " +
         (price - balance) + " more cents.");

}


Self-Review Exercises
Exercise 2.64 List the name and return type of this method:
public String getCode()
{
return code;
}
Answer:
name of the method: getCode
return type of method: String
Exercise 2.65 List the name of this method and the name and type of its parameter:
public void setCredits(int creditValue)
{
credits = creditValue;
}
Answer:
Name of method: SetCredits
Parameter name: creditValue
Parameter type: integer

Exercise 2.66 Write out the outer wrapping of a class called Person. Remember to include the curly brackets that mark the start and end of the class body, but otherwise leave the body empty.
public class Person
{
// code block
}

Exercise 2.67 Write out definitions for the following fields:
■ a field called name of type String
■ a field of type int called age
■ a field of type String called code
■ a field called credits of type int
Answer:
private String name;
private int age;
private String code;
private int credits;
Exercise 2.68 Write out a constructor for a class called Module. The constructor should
take a single parameter of type String called moduleCode. The body of the constructor
should assign the value of its parameter to a field called code. You don’t have to include the definition for code, just the text of the constructor.
public Module(String moduleCode) {
         code = moduleCode;
}
Exercise 2.69 Write out a constructor for a class called Person. The constructor should
take two parameters. The first is of type String and is called myName. The second is of type int and is called myAge. The first parameter should be used to set the value of a field called name, and the second should set a field called age. You don’t have to include the definitions for the fields, just the text of the constructor.
public Person(String myName, int myAge) {
        name = myName;
        age = myAge;
}

Exercise 2.70 Correct the error in this method:
public void getAge()
{
return age;
}
Solution:
public int getAge() {
return age;
}
Exercise 2.71 Write an accessor method called getName that returns the value of a field
called name, whose type is String.
public String getName() {
        return name;
}
Exercise 2.72 Write a mutator method called setAge that takes a single parameter of type int and sets the value of a field called age.
public void setAge(int personAge) {
        age = personAge;
}
Exercise 2.73 Write a method called printDetails for a class that has a field of type
String called name. The printDetails method should print out a string of the form “The
name of this person is”, followed by the value of the name field. For instance, if the value of the name field is “Helen”, then printDetails would print:
The name of this person is Helen
public String printDetails() {
        System.out.println("The name of this person is " + name);
}
Exercise 2.74 Draw a picture of the form shown in Figure 2.3, representing the initial state of a Student object following its construction, with the following actual parameter values:
new Student("Benjamin Jonson", "738321")

Exercise 2.75 What would be returned by getLoginName for a student with name
"Henry Moore" and id "557214"?
Henr557

Exercise 2.76 Create a Student with name "djb" and id "859012". What happens
when getLoginName is called on this student? Why do you think this is?
Get an error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 4 at java.lang.String.substring(String.java:1907)
at Student.getLoginName(Student.java:75)
Because the getLoginName method try to access the student's name starting at index 0 and ending at index 5 but not including 5. djb only has 3 elements with starting index 0 and ending index 3 but not including 3. Index is out of range.

Exercise 2.77 The String class defines a length accessor method with the following
header:
/**
* Return the number of characters in this string.
*/
public int length()
so the following is an example of its use with the String variable fullName:
fullName.length()
Add conditional statements to the constructor of Student to print an error message if
either the length of the fullName parameter is less than four characters or the length of the studentId parameter is less than three characters. However, the constructor should still use those parameters to set the name 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 gave a true result
}
Answer:
public Student(String fullName, String studentID)
{
     if(fullName.length() < 5 || studentID.length() < 4) {
     System.out.println("error");
}
     name = fullName;
     id = studentID;
     credits = 0;

}

Exercise 2.78 Challenge exercise Modify the getLoginName method of Student so
that it always generates a login name, even if either the name or the id field is not strictly long enough. For strings shorter than the required length, use the whole string.
public String getLoginName()
{
    if(name.length() >= 5 && id.length() >= 3){
        return name.substring(0,4) + id.substring(0,3);
}
    else {
        return name.substring(0) + id.substring(0);
}
}

Wednesday, May 7, 2014

Objects first with Java exercises


Exercise 2.52 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.

if(balance >= price) {
    // Simulate the printing of a ticket.
    System.out.println("##################");
    System.out.println("# The BlueJ Line");
    System.out.println("# Ticket");
    System.out.println("# " + price + " cents.");
    System.out.println("##################");
    System.out.println();
    // Update the total collected with the price.
    total = total + price;
    // Reduce the balance by the price.
    balance = balance - price;
}
No because the operation to subtract the value in price by the value in balance will only be executed if there is enough balance in the balance field. Whatever money is in balance; in order to perform the subtraction there has to be an amount greater than or equal to the price of the ticket. The result of the calculation will be whatever is remaining after the purchase of  the ticket. If the ticket cost 50 and the balance is 50 the result will be 0. Whatever is subtracted from balance is never greater than the balance itself; therefore it will never be less than zero (0).


Exercise 2.54 Write an assignment statement that will store the result of multiplying two variables, price and discount, into a third variable, saving.
saving = price * discount;

Exercise 2.55 Write an assignment statement that will divide the value in total by the
value in count and store the result in mean.
mean = total / count;
Exercise 2.56 Write an if statement that will compare the value in price against the value in budget. If price is greater than budget, then print the message “Too expensive”; otherwise print the message “Just right”.
if (price > budget) {
    System.out.println("Too expensive");
}
else {
    System.out.println("Just right");
}
Exercise 2.57 Modify your answer to the previous exercise so that the message includes
the value of your budget if the price is too high.
if (price > budget) {
    System.out.println("Too expensive, you only have: " + budget);
}
else {
    System.out.println("Just right");
}

Exercise 2.58 Why does the following version of refundBalance 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?
It gives a different result because it doesn't take the remaining value after the ticket purchase and store it into a local variable that will be the remaining value used to store the amount to  be refunded. It reassign the balance to zero (0) and doesn't refund anything. The money is then lost and we can say that it steals money from the costumer if the costumer inserts more than the exact value of the ticket price. To see this flaw we call the getBalance method to see the remaining balance and  then call the refundBalance method to see that the current balance wasn't returned as a refund to the user.
Exercise 2.59 What happens if you try to compile the TicketMachine class with the following version of refundBalance?
public int refundBalance()
{
    return balance;
    balance = 0;
}
What do you know about return statements that helps to explain why this version does not compile?
The compiler won't compile because there is an unreachable statement.
A return statement should be the last statement within the code block. Anything  after return will be unreachable. The return statement tells the method to exit; therefore anything after it won't be reachable.

Exercise 2.60 What is wrong with the following version of the constructor of TicketMachine?
public TicketMachine(int cost)
{
    int price = cost;
    balance = 0;
    total = 0;
}
Does this version compile? Create an object and then inspect its fields. Do you notice something wrong about the value of the price field in the inspector with this version? Can you explain why this is?
The  program compiles but the value in cost is not stored in a field, it is stored in a local variable that only holds the value temporarily. A local variable last as long as a the execution of the method it belongs to lasts. If we call the getPrice method after creating an object from the TicketMachine class and we pass in a value through the cost parameter, that value will be zero(0) because the getPrice accessor returns the value stored in the price field and we haven't supply any value to it. The value we enter when we constructed the object was store into the price local variable and not the price field because A local variable of the same name as a field will prevent the field being accessed from within a constructor or method.

Exercise 2.61 Add a new method, emptyMachine, that is designed to simulate emptyingthe machine of money. It should reset total to be zero but also return the value that was stored in total before it was reset.
public int emptyMachine() {
    int oldTotal;
    oldTotal = total;
    total = 0;
    return oldTotal;
}

to be continued...