Main Menu

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

Saturday, May 3, 2014

Objects first with Java notes

Chapter One

Java Objects model objects from a problem domain. Objects are created from classes. The Class describe the kind of object; the object represent individual instantiations of the class. Objects can be categorized as all objects of a particular kind.
When talking in general; we are dealing with a class and when we are talking about a particular object; we are dealing with an object; an instance of a class.

in object-oriented programming we refer to a object as an instance. "Instance" is roughly a synonyms with "object"; when pointing out that the object is an instance of a particular class.

We communicate with Objects by invoking methods on them. Objects behave or do something if we invoke a method. A method represent the behavior of an object.

Methods can have parameters to provide additional information for a task. Methods may require additional information; the additional information are called parameters. Parameters define a 'type' and 'name'. Parameters have types; the type defines what kinds of values the parameter takes.

The header of a method is call signature. It provide information needed to invoke that method. For example, the method moveHorizontal(int distance). moveHorizontal is the signature of the method and the information in between parenthesis tells us what kind of information the method takes; in this example, it takes type of integer; int for integer. a numeral data type.

If method has no parameters, the method is followed by a pair of empty parenthesis.

Multiple instances can be created from single class. Instances are objects of a class. If I have class cars I can create many car objects as I like; these car objects are instances of  the class cars. 

State
The set of values that define an object's attributes is called the state of an object. E.g. (x-position, y-position, color, diameter, shape, visibility, etc.) The state of an object is determined by storing the values in fields, variables in some other languages.

Some methods, when called change the state of an object; for instance if I have a object named ball and called a method moveRight(). The moveRight method will change the state of the object ball; the ball's position will change.

Objects of the same class all share the same fields, the value of a particular field may vary; but the name, number and type of the field are the same because objects of the same class share the same attributes; the attributes in an object are defined in the class that they're created from and are not defined from the object itself. The same goes with methods

Date types

Int is a numerical data type; String is also a kind of data type, strings can be anything within double quotation marks: " I am a string 12444, %%$&^^"

Exercise 1.9

Choose from one of the images below and achieve the same output; write down what you needed to do in order to achieve this.



I chose the one to the right and modified the position of the sun to fit my own desires.
For this exercise I did the following:

  1. From the Class circle I created 4 objects
  2. First object: I named it groundCircle.  I made the object visible and gave it a diameter or a 1000 pixels with a xposition of -270 and a yposition of 190 to center it, and I finally colored it green to make look like the above picture.
  3. From the same package where the Class Circle belongs to, I created 2 objects of type person; one smaller than the other. Each person object has the same fields with different values: Height, Width, Xposition, Yposition, Color and isVisible. The value differ as each person object.
  4. Finally, I created another object from the same Class obviously. I called is sunCircle to represent the sun. The sunCircle has the attributes as the groundCircle with different values make it appropriate for this exercise.

Here is my version: