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();
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();
{
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;
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.");
}
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;
}
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;
}
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
■ 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.
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.
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;
}
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.
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.
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
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")
new Student("Benjamin Jonson", "738321")
Exercise 2.75 What would be returned by getLoginName for a student with name
"Henry Moore" and id "557214"?
"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)
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()
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
}
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;
}
{
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.
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);
}
}
{
if(name.length() >= 5 && id.length() >= 3){
return name.substring(0,4) + id.substring(0,3);
}
else {
return name.substring(0) + id.substring(0);
}
}