Chapter 2

Exercise 2.2

Zero.

Exercise 2.3

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

It looks the same. Only the price on the ticket is different.

Exercise 2.6

The outer part of the student class:
public class Student {
}
The outer part of the LabClass class:
public class LabClass{
}
Exercise 2.7

Fields:
price
balance
total

Constructors:
TicketMachine

Methods:
getPrice
getBalance
insertMoney
printTicket
Exercise 2.8

It does not have any return type. The name of the constructor is the same as the name of the class.
Exercise 2.9

The only difference is that getPrice() returns the price and getBalance returns the balance
Exercise 2.10

How much money have I inserted into the machine?
Exercise 2.11

No.
Exercise 2.12
public int getTotal() { 
    return total;
} 
Exercise 2.13

Missing return statement.
Exercise 2.14

The signature for getPrice() has an int as return type.
The signature for printTicket has void as return type.
Exercise 2.15

No.
Because they don't need to return anything.
Yes. Both headers has void as return types.
Exercise 2.18

It shows the amount of money that was inserted with the last call to insertMoney()
Exercise 2.19
public void prompt() {
    System.out.println("Please insert the correct amount of money.");
}					 
Exercise 2.20
public void showPrice() {
    System.out.println("The price of a ticket is " + price + " cents");
}				  
Exercise 2.21

They display different prices. This is because each ticketmachine object has its own price.
The price that was set in one ticketmachine does not affect the other ticketmachines price.
Exercise 2.22

Instead of printing out the actual price of the ticket, it just displays the word "price".
Exercise 2.23

Prints out the exact same string as in exercise 2.22
Exercise 2.24

No. None of them actually displays the price of the ticket.
Exercise 2.25
public TicketMachine()
{
    price = 1000;
    balance = 0;
    total = 0;
}				  
The tickets always have a price of 1000.
Exercise 2.26
public void empty() {
    total = 0; 
}				  
It needs no parameters.
It is a mutator.
Exercise 2.27
public void setPrice(int newPrice) {
    price = newPrice;
}				 
It is a mutator.
Exercise 2.28
public TicketMachine()
{
    price = 1000;
    balance = 0;
    total = 0;
}				 
	
public TicketMachine(int ticketCost)
{
    price = ticketCost;
    balance = 0;
    total = 0;
}				  
Exercise 2.29

The balance does not change when an error message is printed.
Inserting 0, results in an error message.
Exercise 2.30

It does not print an error message.
It does not change the behavior of the method.
Exercise 2.31

The field is: isVisible.
It determeines whether the circle was visible or not.
Yes. As circle is either visible or not, only two states(values) are needed.
Exercise 2.32

In the printTicket method of Code 2.8 the total is increased with the price of the ticket, and not the balance.
The balance is then decreased with the price.
Exercise 2.33

No the balance can not be negative. The price is substracted from the balance inside the body of a conditaional statement, that only is entered if the balance is at least the same as the price of a ticket.
Exercise 2.34

Because balance is set to zero and then thsi value is returned. Themethod will always return zero. It can be testet by inserting an amount, and then calling refundBalance(). The original would then return the amount inserted, but the new method returns 0.
Exercise 2.35

An error is printed: unreachable statement.
A return statement ends(exits) the method. Code after a return statement can therefor never be executed.
Exercise 2.36

public int emptyMachine() {
    int oldTotal = total;
    total = 0;
    return oldTotal;
}				  
Exercise 2.37

It is both an accessor and a mutator.
Exercise 2.38
public void printTicket()
{
	int amountLeftToPay = price - balance;
	if(amountLeftToPay <= 0) {
		// 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 += price;
		// Reduce the balance by the prince.
		balance -= price;
	}
	else {
		System.out.println("You must insert at least: " +
						   amountLeftToPay + " more cents.");
				
	}
}				 
Exercise 2.39

student1 : Student
name: Benjamin Johnson
id: 738321
credits: 0
Exercise 2.40

"Henr557"
Exercise 2.41

It opens the editor with the source code for the Student class. It displays a message: StringIndexOutOfBoundsException
This happens because the method getLoginName expects the name to be at lesat 4 charaters long and "djb" is only 3 characters.
Exercise 2.42
public Student(String fullName, String studentID)
{
	if(fullName.length() < 4) {
		System.out.println("Error! The name should be at least 4 characters long");
	}
	if(studentID.length() < 3) {
		System.out.println("Error! The studentID should be at least 3 characters long");
	}
	
	name = fullName;
	id = studentID;
	credits = 0;
}				
Exercise 2.43
public String getLoginName()
{
	String loginNamePart;
	if(name.length() < 4) {
		loginNamePart = name;
	} else {
		loginNamePart = name.substring(0,4);
	}
	
	String loginIdPart;
	if(id.length() < 3) {
		loginIdPart = id;
	} else {
		loginIdPart = id.substring(0,3);
	}
	
	return  loginNamePart + loginIdPart ;
}				  
Exercise 2.44
/**
 * Returns the author of this book.
 */
public String getAuthor() {
	return author;
}

/**
 *  Returns the title of this book.
 */
public String getTitle() {
	return title;
}			  
Exercise 2.45
/**
 * Prints the name of the author in the terminal window.
 */
public void printAuthor() {
	System.out.println("Author: " + author);
}    

/**
 * Prints the title of the book in the terminal window.
 */
public void printTitle() {
	System.out.println("Title: " + title);
}				  
Exercise 2.46

Delete the constructor and insert this:
private int pages;

/**
 * Set the author and title fields when this object
 * is constructed.
 */
public Book(String bookAuthor, String bookTitle, int bookPages)
{
	author = bookAuthor;
	title = bookTitle;
	pages = bookPages;
}

/**
 * Returns the number of pages in this book.
 */
public int getPages() {
	return pages;
}				  
Exercise 2.47
public void printDetails(){
	System.out.println("Title:  " + title);
	System.out.println("Author: " + author);
	System.out.println("Pages:  " + pages);
}				  
Exercise 2.48

Delete the constructor and insert:
private String refNumber;

/**
 * Set the author and title fields when this object
 * is constructed.
 */
public Book(String bookAuthor, String bookTitle, int bookPages)
{
	author = bookAuthor;
	title = bookTitle;
	pages = bookPages;
	refNumber = "";
}

/**
 * Sets the reference number fot this book
 */
public void setRefNumber(String ref) {
	refNumber = ref;        
}

/**
 * Gets the reference number fot this book
 */
public String getRefNumber() {
	return refNumber;
}					
Exercise 2.49

public void printDetails() {
	System.out.println("Title:  " + title);
	System.out.println("Author: " + author);
	System.out.println("Pages:  " + pages);
	
	String refNumberString; 
	if(refNumber.length() > 0 ) {
		refNumberString = refNumber;
	} else {
		refNumberString = "ZZZ";
	}
	System.out.println("Reference number:  " + refNumberString);        
}				  
Exercise 2.50

public void setRefNumber(String ref) {
	if(ref.length() > 2) {
		refNumber = ref;     
	}
	else {
		System.out.println("Error! The reference number must be at least 3 characters long.");
	}
}				  
Exercise 2.51

Add the field:
private int borrowed;
					
Add the methods:
/** 
 * Borrows the book. Increments the number of times the book has been borrowed.
 */
public void borrow() {
	borrowed++;
}

/**
 * Gets the number of times the book has been borrowed.
 */
public int getBorrowed() {
	return borrowed;
}					
Add this line to printDetails method:
System.out.println("Borrowed: " + borrowed);

Exercise 2.53

public class Heater
{
    private int temperature;

    /**
    *  Creates a new Heater with an initial temperature of 15.
    */
	public Heater() {
		temperature = 15;
	}

	/**
	* Increases the temperature by 5 degrees
	*/ 
	public void warmer() {
		temperature += 5;
	}
	
	/**
	* Decreases the temperature by 5 degrees
	*/ 
	public void cooler() {
		temperature -= 5;
	}
	
	/**
	* Gets the current temperature of the heater
	*/
	public int getTemperature() {
		return temperature;
	}
}				

Exercise 2.52

public class Heater
{
    private int temperature;
    private int min;
    private int max;
    private int increment;
    
    
    /**
     *  Creates a new Heater with an initial temperature of 15.
     */
    public Heater(int minimum, int maximum) {
        min = minimum;
        max = maximum;
        temperature = 15;
        increment = 5;
    }
    
    /**
     * Increases the temperature
     */ 
    public void warmer() {
        int newTemperature = temperature + increment;
        if(newTemperature <= max) {
            temperature = newTemperature;
        }
    }
    
    /**
     * Decreases the temperature
     */ 
    public void cooler() {
        int newTemperature = temperature - increment;
        if(newTemperature >= min) {
            temperature = newTemperature;
        }
    }
    
    /**
     * Sets the increment, which determines how much the two methods 
     * warmer() and cooler() changes the temperature.
     */
    public void setIncrement(int inc)  {
        if(inc >= 0) {
            increment = inc;
        }
    }
    
    /**
     * Gets the current temperature of the heater
     */
    public int getTemperature() {
        return temperature;
    }
}				
If the setIncrement method does not check for negative values, and a negative value is passed, then the program will not work as expected. The minimum and maximum values can be exceeded.