100% found this document useful (4 votes)
101 views58 pages

Java Software Solutions 9th Edition Lewis Solutions Manualinstant download

The document provides links to download solutions manuals and test banks for various editions of 'Java Software Solutions' by Lewis, as well as other educational resources. It includes programming exercises related to object-oriented design concepts such as parameter passing, interfaces, and class modifications. Additionally, it contains code examples demonstrating these concepts through practical applications in Java.

Uploaded by

iqbalmalcri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
101 views58 pages

Java Software Solutions 9th Edition Lewis Solutions Manualinstant download

The document provides links to download solutions manuals and test banks for various editions of 'Java Software Solutions' by Lewis, as well as other educational resources. It includes programming exercises related to object-oriented design concepts such as parameter passing, interfaces, and class modifications. Additionally, it contains code examples demonstrating these concepts through practical applications in Java.

Uploaded by

iqbalmalcri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Java Software Solutions 9th Edition Lewis

Solutions Manual pdf download

https://testbankfan.com/product/java-software-solutions-9th-
edition-lewis-solutions-manual/
We believe these products will be a great fit for you. Click
the link to download now, or visit testbankfan.com
to discover even more!

Java Software Solutions 9th Edition Lewis Test Bank

https://testbankfan.com/product/java-software-solutions-9th-
edition-lewis-test-bank/

Java Software Solutions 8th Edition Lewis Solutions


Manual

https://testbankfan.com/product/java-software-solutions-8th-
edition-lewis-solutions-manual/

Java Software Solutions 8th Edition Lewis Test Bank

https://testbankfan.com/product/java-software-solutions-8th-
edition-lewis-test-bank/

Infants Children and Adolescents and MyVirtualChild 7th


Edition Berk Test Bank

https://testbankfan.com/product/infants-children-and-adolescents-
and-myvirtualchild-7th-edition-berk-test-bank/
Language Of Medicine 11th Edition Chabner Test Bank

https://testbankfan.com/product/language-of-medicine-11th-
edition-chabner-test-bank/

Understanding Nutrition Canadian 2nd Edition Whitney


Solutions Manual

https://testbankfan.com/product/understanding-nutrition-
canadian-2nd-edition-whitney-solutions-manual/

Managerial Accounting Asia Pacific 1st Edition Mowen


Solutions Manual

https://testbankfan.com/product/managerial-accounting-asia-
pacific-1st-edition-mowen-solutions-manual/

Interpersonal Messages 4th Edition Devito Test Bank

https://testbankfan.com/product/interpersonal-messages-4th-
edition-devito-test-bank/

Essentials of Biology 4th Edition Mader Test Bank

https://testbankfan.com/product/essentials-of-biology-4th-
edition-mader-test-bank/
Principles of Macroeconomics 7th Edition Taylor Test
Bank

https://testbankfan.com/product/principles-of-macroeconomics-7th-
edition-taylor-test-bank/
Chapter 7: Object-Oriented Design Lab Exercises
Topics Lab Exercises
Parameter Passing Changing People

Interfaces Using the Comparable Interface

Method Decomposition A Modified MiniQuiz Class

Overloading A Flexible Account Class


A Biased Coin

Static Variables and Methods Opening and Closing Accounts


Counting Transactions
Transfering Funds

Overall class design Random Walks

GUI Layouts Telephone Keypad

102 Chapter 7: Object-Oriented Design


Changing People
The file ChangingPeople.java contains a program that illustrates parameter passing. The program uses Person objects
defined in the file Person.java. Do the following:
1. Trace the execution of the program using diagrams similar to those in Figure 6.5 of the text (which is a trace of the
program in Listings 6.15–6.17). Also show what is printed by the program.
2. Compile and run the program to see if your trace was correct.
3. Modify the changePeople method so that it does what the documentation says it does, that is, the two Person objects
passed in as actual parameters are actually changed.

// ******************************************************************
// ChangingPeople.java
//
// Demonstrates parameter passing -- contains a method that should
// change to Person objects.
// ******************************************************************

public class ChangingPeople


{
// ---------------------------------------------------------
// Sets up two person objects, one integer, and one String
// object. These are sent to a method that should make
// some changes.
// ---------------------------------------------------------
public static void main (String[] args)
{
Person person1 = new Person ("Sally", 13);
Person person2 = new Person ("Sam", 15);

int age = 21;


String name = "Jill";

System.out.println ("\nParameter Passing... Original values...");


System.out.println ("person1: " + person1);
System.out.println ("person2: " + person2);
System.out.println ("age: " + age + "\tname: " + name + "\n");

changePeople (person1, person2, age, name);

System.out.println ("\nValues after calling changePeople...");


System.out.println ("person1: " + person1);
System.out.println ("person2: " + person2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
}

// -------------------------------------------------------------------
// Change the first actual parameter to "Jack - Age 101" and change
// the second actual parameter to be a person with the age and
// name given in the third and fourth parameters.
// -------------------------------------------------------------------
public static void changePeople (Person p1, Person p2, int age, String name)
{
System.out.println ("\nInside changePeople... Original parameters...");
System.out.println ("person1: " + p1);
System.out.println ("person2: " + p2);
System.out.println ("age: " + age + "\tname: " + name + "\n");

Chapter 7: Object-Oriented Design 103


// Make changes
Person p3 = new Person (name, age);
p2 = p3;
name = "Jack";
age = 101;
p1.changeName (name);
p1.changeAge (age);

// Print changes
System.out.println ("\nInside changePeople... Changed values...");
System.out.println ("person1: " + p1);
System.out.println ("person2: " + p2);
System.out.println ("age: " + age + "\tname: " + name + "\n");
}
}

// ************************************************************
// Person.java
//
// A simple class representing a person.
// ************************************************************
public class Person
{
private String name;
private int age;

// ----------------------------------------------------------
// Sets up a Person object with the given name and age.
// ----------------------------------------------------------
public Person (String name, int age)
{
this.name = name;
this.age = age;
}

// ----------------------------------------------------------
// Changes the name of the Person to the parameter newName.
// ----------------------------------------------------------
public void changeName(String newName)
{
name = newName;
}

// ----------------------------------------------------------
// Changes the age of the Person to the parameter newAge.
// ----------------------------------------------------------
public void changeAge (int newAge)
{
age = newAge;
}

// ----------------------------------------------------------
// Returns the person's name and age as a string.
// ----------------------------------------------------------
public String toString()
{
return name + " - Age " + age;
}
}
104 Chapter 7: Object-Oriented Design
Using the Comparable Interface
1. Write a class Compare3 that provides a static method largest. Method largest should take three Comparable parameters
and return the largest of the three (so its return type will also be Comparable). Recall that method compareTo is part of
the Comparable interface, so largest can use the compareTo method of its parameters to compare them.

2. Write a class Comparisons whose main method tests your largest method above.
• First prompt the user for and read in three strings, use your largest method to find the largest of the three strings, and
print it out. (It’s easiest to put the call to largest directly in the call to println.) Note that since largest is a static
method, you will call it through its class name, e.g., Compare3.largest(val1, val2, val3).
• Add code to also prompt the user for three integers and try to use your largest method to find the largest of the three
integers. Does this work? If it does, it’s thanks to autoboxing, which is Java 1.5’s automatic conversion of ints to
Integers. You may have to use the -source 1.5 compiler option for this to work.

Chapter 7: Object-Oriented Design 105


A Modified MiniQuiz Class
Files Question.java, Complexity.java, and MiniQuiz.java contain the classes in Listings 6.8-6.10of the text. These classes
demonstrate the use of the Complexity interface; class Question implements the interface, and class MiniQuiz creates two
Question objects and uses them to give the user a short quiz.

Save these three files to your directory and study the code in MiniQuiz.java. Notice that after the Question objects are
created, almost exactly the same code appears twice, once to ask and grade the first question, and again to ask and grade the
second question. Another approach is to write a method askQuestion that takes a Question object and does all the work of
asking the user the question, getting the user’s response, and determining whether the response is correct. You could then
simply call this method twice, once for q1 and once for q2. Modify the MiniQuiz class so that it has such an askQuestion
method, and replace the code in main that asks and grades the questions with two calls to askQuestion. Some things to keep
in mind:

The definition of askQuestion should be inside the MiniQuiz class but after the main method.
Since main is a static method, askQuestion must be static too. (A static method cannot call an instance method of the
same class.) Also, askQuestion is for use only by this class, so it should be declared private. So the header for
askQuestion should look like this:

private static void askQuestion(Question question)

• String possible, which is currently declared in main, will need to be defined in askQuestion instead.
• The Scanner object scan needs to be a static variable and moved outside of main (so it is available to askQuestion).
• You do not need to make any changes to Question.java or Complexity .java.

//****************************************************************
// Question.java Author: Lewis/Loftus
//
// Represents a question (and its answer).
//****************************************************************

public class Question implements Complexity


{
private String question, answer;
private int complexityLevel;

//--------------------------------------------------------------
// Sets up the question with a default complexity.
//--------------------------------------------------------------
public Question (String query, String result)
{
question = query;
answer = result;
complexityLevel = 1;
}

//--------------------------------------------------------------
// Sets the complexity level for this question.
//--------------------------------------------------------------
public void setComplexity (int level)
{
complexityLevel = level;
}

//--------------------------------------------------------------
// Returns the complexity level for this question.
//--------------------------------------------------------------
public int getComplexity()

106 Chapter 7: Object-Oriented Design


{
return complexityLevel;
}

//--------------------------------------------------------------
// Returns the question.
//--------------------------------------------------------------
public String getQuestion()
{
return question;
}

//--------------------------------------------------------------
// Returns the answer to this question.
//--------------------------------------------------------------
public String getAnswer()
{
return answer;
}

//--------------------------------------------------------------
// Returns true if the candidate answer matches the answer.
//--------------------------------------------------------------
public boolean answerCorrect (String candidateAnswer)
{
return answer.equals(candidateAnswer);
}

//--------------------------------------------------------------
// Returns this question (and its answer) as a string.
//--------------------------------------------------------------
public String toString()
{
return question + "\n" + answer;
}
}

//*****************************************************************
// Complexity.java Author: Lewis/Loftus
//
// Represents the interface for an object that can be assigned an
// explicit complexity.
//*****************************************************************

public interface Complexity


{
public void setComplexity (int complexity);
public int getComplexity();
}

Chapter 7: Object-Oriented Design 107


//*****************************************************************
// MiniQuiz.java Author: Lewis/Loftus
//
// Demonstrates the use of a class that implements an interface.
//*****************************************************************

import java.util.Scanner;

public class MiniQuiz


{
//--------------------------------------------------------------
// Presents a short quiz.
//--------------------------------------------------------------
public static void main (String[] args)
{
Question q1, q2;
String possible;

Scanner scan = new Scanner(System.in);

q1 = new Question ("What is the capital of Jamaica?",


"Kingston");
q1.setComplexity (4);
q2 = new Question ("Which is worse, ignorance or apathy?",
"I don't know and I don't care");
q2.setComplexity (10);

System.out.print (q1.getQuestion());
System.out.println (" (Level: " + q1.getComplexity() + ")");
possible = scan.nextLine();
if (q1.answerCorrect(possible))
System.out.println ("Correct");
else
System.out.println ("No, the answer is " + q1.getAnswer());

System.out.println();
System.out.print (q2.getQuestion());
System.out.println (" (Level: " + q2.getComplexity() + ")");
possible = scan.nextLine();
if (q2.answerCorrect(possible))
System.out.println ("Correct");
else
System.out.println ("No, the answer is " + q2.getAnswer ());
}
}

108 Chapter 7: Object-Oriented Design


A Flexible Account Class
File Account.java contains a definition for a simple bank account class with methods to withdraw, deposit, get the balance
and account number, and return a String representation. Note that the constructor for this class creates a random account
number. Save this class to your directory and study it to see how it works. Then modify it as follows:

1. Overload the constructor as follows:

• public Account (double initBal, String owner, long number) - initializes the balance, owner, and account
number as specified
• public Account (double initBal, String owner) - initializes the balance and owner as specified; randomly
generates the account number.
• public Account (String owner) - initializes the owner as specified; sets the initial balance to 0 and randomly
generates the account number.

2. Overload the withdraw method with one that also takes a fee and deducts that fee from the account.

File TestAccount.java contains a simple program that exercises these methods. Save it to your directory, study it to see what
it does, and use it to test your modified Account class.

//************************************************************
// Account.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//************************************************************

public class Account


{
private double balance;
private String name;
private long acctNum;

//-------------------------------------------------
//Constructor -- initializes balance, owner, and account number
//-------------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}

//-------------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//-------------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}

//-------------------------------------------------
// Adds deposit amount to balance.
//-------------------------------------------------

Chapter 7: Object-Oriented Design 109


public void deposit(double amount)
{
balance += amount;
}

//-------------------------------------------------
// Returns balance.
//-------------------------------------------------
public double getBalance()
{
return balance;
}

//-------------------------------------------------
// Returns a string containing the name, account number, and balance.
//-------------------------------------------------
public String toString()
{
return "Name:" + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}

//************************************************************
// TestAccount.java
//
// A simple driver to test the overloaded methods of
// the Account class.
//************************************************************

import java.util.Scanner;

public class TestAccount


{
public static void main(String[] args)
{
String name;
double balance;
long acctNum;
Account acct;

Scanner scan = new Scanner(System.in);

System.out.println("Enter account holder's first name");


name = scan.next();
acct = new Account(name);
System.out.println("Account for " + name + ":");
System.out.println(acct);

System.out.println("\nEnter initial balance");


balance = scan.nextDouble();
acct = new Account(balance,name);
System.out.println("Account for " + name + ":");
System.out.println(acct);

110 Chapter 7: Object-Oriented Design


System.out.println("\nEnter account number");
acctNum = scan.nextLong();
acct = new Account(balance,name,acctNum);
System.out.println("Account for " + name + ":");
System.out.println(acct);

System.out.print("\nDepositing 100 into account, balance is now ");


acct.deposit(100);
System.out.println(acct.getBalance());
System.out.print("\nWithdrawing $25, balance is now ");
acct.withdraw(25);
System.out.println(acct.getBalance());
System.out.print("\nWithdrawing $25 with $2 fee, balance is now ");
acct.withdraw(25,2);
System.out.println(acct.getBalance());

System.out.println("\nBye!");
}
}

Chapter 7: Object-Oriented Design 111


Modifying the Coin Class
1. Create a new class named BiasedCoin that models a biased coin (heads and tails are not equally likely outcomes of a
flip). To do this modify the coin class from the Listing 5.4 of text (in the file Coin.java) as follows:
Add a private data member bias of type double. This data member will be a number between 0 and 1 (inclusive) that
represents the probability the coin will be HEADS when flipped. So, if bias is 0.5, the coin is an ordinary fair coin.
If bias is 0.6, the coin has probability 0.6 of coming up heads (on average, it comes up heads 60% of the time).
Modify the default constructor by assigning the value 0.5 to bias before the call to flip. This will make the default
coin a fair one.
Modify flip so that it generates a random number then assigns face a value of HEADS if the number is less than the
bias; otherwise it assigns a value of TAILS.
Add a second constructor with a single double parameter—that parameter will be the bias. If the parameter is valid
(a number between 0 and 1 inclusive) the constructor should assign the bias data member the value of the parameter;
otherwise it should assign bias a value of 0.5. Call flip (as the other constructor does) to initialize the value of face.

2. Compile your class to make sure you have no syntax errors.

3. Write a program that uses three BiasedCoin objects. Instantiate one as a fair coin using the constructor with no
parameter. Read in the biases for the other two coins and instantiate those coins using the constructor with the bias as a
parameter. Your program should then have a loop that flips each coin 100 times and counts the number of times each is
heads. After the loop print the number of heads for each coin. Run the program several times testing out different biases.

112 Chapter 7: Object-Oriented Design


Opening and Closing Accounts
File Account.java (see previous exercise) contains a definition for a simple bank account class with methods to withdraw,
deposit, get the balance and account number, and return a String representation. Note that the constructor for this class
creates a random account number. Save this class to your directory and study it to see how it works. Then write the following
additional code:

1. Suppose the bank wants to keep track of how many accounts exist.

a. Declare a private static integer variable numAccounts to hold this value. Like all instance and static variables, it will
be initialized (to 0, since it’s an int) automatically.
b. Add code to the constructor to increment this variable every time an account is created.
c. Add a static method getNumAccounts that returns the total number of accounts. Think about why this method should
be static - its information is not related to any particular account.
d. File TestAccounts1.java contains a simple program that creates the specified number of bank accounts then uses the
getNumAccounts method to find how many accounts were created. Save it to your directory, then use it to test your
modified Account class.

2. Add a method void close() to your Account class. This method should close the current account by appending
“CLOSED” to the account name and setting the balance to 0. (The account number should remain unchanged.) Also
decrement the total number of accounts.

3. Add a static method Account consolidate(Account acct1, Account acct2) to your Account class that creates a new
account whose balance is the sum of the balances in acct1 and acct2 and closes acct1 and acct2. The new account should
be returned. Two important rules of consolidation:

• Only accounts with the same name can be consolidated. The new account gets the name on the old accounts but a new
account number.
• Two accounts with the same number cannot be consolidated. Otherwise this would be an easy way to double your
money!

Check these conditions before creating the new account. If either condition fails, do not create the new account or close
the old ones; print a useful message and return null.

4. Write a test program that prompts for and reads in three names and creates an account with an initial balance of $ 100 for
each. Print the three accounts, then close the first account and try to consolidate the second and third into a new account.
Now print the accounts again, including the consolidated one if it was created.

//************************************************************
// TestAccounts1
// A simple program to test the numAccts method of the
// Account class.
//************************************************************
import java.util.Scanner;

public class TestAccounts1


{
public static void main(String[] args)
{
Account testAcct;

Scanner scan = new Scanner(System.in);

Chapter 7: Object-Oriented Design 113


System.out.println("How many accounts would you like to create?"); int num =
scan.nextInt();

for (int i=1; i<=num; i++)


{
testAcct = new Account(100, "Name" + i);
System.out.println("\nCreated account " + testAcct);
System.out.println("Now there are " + Account.numAccounts () +
" accounts");
}
}
}

114 Chapter 7: Object-Oriented Design


Counting Transactions
File Account.java (see A Flexible Account Class exercise) contains a definition for a simple bank account class with
methods to withdraw, deposit, get the balance and account number, and return a String representation. Note that the
constructor for this class creates a random account number. Save this class to your directory and study it to see how it works.
Now modify it to keep track of the total number of deposits and withdrawals (separately) for each day, and the total amount
deposited and withdrawn. Write code to do this as follows:

1. Add four private static variables to the Account class, one to keep track of each value above (number and total amount of
deposits, number and total of withdrawals). Note that since these variables are static, all of the Account objects share
them. This is in contrast to the instance variables that hold the balance, name, and account number; each Account has its
own copy of these. Recall that numeric static and instance variables are initialized to 0 by default.

2. Add public methods to return the values of each of the variables you just added, e.g., public static int getNumDeposits().

3. Modify the withdraw and deposit methods to update the appropriate static variables at each withdrawal and deposit

4. File ProcessTransactions.java contains a program that creates and initializes two Account objects and enters a loop that
allows the user to enter transactions for either account until asking to quit. Modify this program as follows:
After the loop, print the total number of deposits and withdrawals and the total amount of each. You will need to use
the Account methods that you wrote above. Test your program.
Imagine that this loop contains the transactions for a single day. Embed it in a loop that allows the transactions to be
recorded and counted for many days. At the beginning of each day print the summary for each account, then have
the user enter the transactions for the day. When all of the transactions have been entered, print the total numbers
and amounts (as above), then reset these values to 0 and repeat for the next day. Note that you will need to add
methods to reset the variables holding the numbers and amounts of withdrawals and deposits to the Account class.
Think: should these be static or instance methods?

//************************************************************
// ProcessTransactions.java
//
// A class to process deposits and withdrawals for two bank
// accounts for a single day.
//************************************************************
import java.util.Scanner;

public class ProcessTransactions


{
public static void main(String[] args){

Account acct1, acct2; //two test accounts


String keepGoing = "y"; //more transactions?
String action; //deposit or withdraw
double amount; //how much to deposit or withdraw
long acctNumber; //which account to access

Scanner scan = new Scanner(System.in);

//Create two accounts


acct1 = new Account(1000, "Sue", 123);
acct2 = new Account(1000, "Joe", 456);

System.out.println( "The following accounts are available: \n" );


acct1.printSummary();

System.out.println();
acct2.printSummary();

Chapter 7: Object-Oriented Design 115


while (keepGoing.equals("y") || keepGoing.equals("y"))
{
//get account number, what to do, and amount
System.out.print("\nEnter the number of the account you would like
to access: ");
acctNumber = scan.nextLong();
System.out.print("Would you like to make a deposit (D) or withdrawal
(W) ? ");
action = scan.next();
System.out.print("Enter the amount: ");
amount = scan.nextDouble();

if (amount > 0)
if (acctNumber == acct1.getAcctNumber())
if (action.equals("w") || action.equals("W"))
acct1.withdraw(amount);
else if (action.equals("d") || action.equals("D"))
acct1.deposit(amount);
else
System.out.println("Sorry, invalid action.");
else if (acctNumber == acct2.getAcctNumber())
if (action.equals("w") || action.equals("W"))
acct1.withdraw(amount);
else if (action.equals("d") || action.equals("D"))
acct1.deposit(amount);
else
System.out.println( "Sorry, invalid action. ");
else
System.out.println( "Sorry, invalid account number. ");

else
System.out.println("Sorry, amount must be > 0 . ");

System.out.print("\nMore transactions? (y/n)");


keepGoing = scan.next();
}

//Print number of deposits


//Print number of withdrawals
//Print total amount of deposits
//Print total amount of withdrawals

}
}

116 Chapter 7: Object-Oriented Design


Transfering Funds
File Account.java (see A Flexible Account Class exercise) contains a definition for a simple bank account class with
methods to withdraw, deposit, get the balance and account number, and print a summary. Save it to your directory and study
it to see how it works. Then write the following additional code:

1. Add a method public void transfer(Account acct, double amount) to the Account class that allows the user to transfer
funds from one bank account to another. If acct1 and acct2 are Account objects, then the call
acct1.transfer(acct2,957.80) should transfer $957.80 from acct1 to acct2. Be sure to clearly document which way the
transfer goes!

2. Write a class TransferTest with a main method that creates two bank account objects and enters a loop that does the
following:
Asks if the user would like to transfer from account1 to account2, transfer from account2 to account1, or quit.
If a transfer is chosen, asks the amount of the transfer, carries out the operation, and prints the new balance for each
account.
Repeats until the user asks to quit, then prints a summary for each account.

3. Add a static method to the Account class that lets the user transfer money between two accounts without going through
either account. You can (and should) call the method transfer just like the other one - you are overloading this method.
Your new method should take two Account objects and an amount and transfer the amount from the first account to the
second account. The signature will look like this:

public static void transfer(Account acct1, Account acct2, double amount)

Modify your TransferTest class to use the static transfer instead of the instance version.

Chapter 7: Object-Oriented Design 117


Random Walks
In this lab you will develop a class that models a random walk and write two client programs that use the class. A random
walk is basically a sequence of steps in some enclosed space where the direction of each step is random. The walk terminates
either when a maximum number of steps has been taken or a step goes outside of the boundary of the space. Random walks
are used to model physical phenomena such as the motion of molecules and economic phenomena such as stock prices.

We will assume that the random walk takes place on a square grid with the point (0,0) at the center. The boundary of the
square will be a single integer that represents the maximum x and y coordinate for the current position on the square (so for a
boundary value of 10, both the x and y coordinates can vary from -10 to 10, inclusive). Each step will be one unit up, one unit
down, one unit to the left, or one unit to the right. (No diagonal movement.)

The RandomWalk class will have the following instance data (all type int):

• the x coordinate of the current position


• the y coordinate of the current position
• the maximum number of steps in the walk
• the number of steps taken so far in the walk
• the boundary of the square (a positive integer -- the x and y coordinates of the position can vary between plus and
minus this value)

Create a new file RandomWalk.java. You’ll define the RandomWalk class incrementally testing each part as you go.
1. First declare the instance data (as described above) and add the following two constructors and toString method.
 RandomWalk (int max, int edge) - Initializes the RandomWalk object. The maximum number of steps and
the boundary are given by the parameters. The x and y coordinates and the number of steps taken should be
set to 0.
 RandomWalk (int max, int edge, int startX, int startY) -- Initializes the maximum number of steps, the
boundary, and the starting position to those given by the parameters.
 String toString() - returns a String containing the number of steps taken so far and the current position --
The string should look something like: Steps: 12; Position: (-3,5)
2. Compile what you have so far then open the file TestWalk.java. This file will be used to test your RandomWalk
methods. So far it prompts the user to enter a boundary, a maximum number of steps, and the x and y coordinates of
a position. Add the following:
 Declare and instantiate two RandomWalk objects -- one with boundary 5, maximum steps 10, and centered
at the origin (use the two parameter constructor) and the other with the values entered by the user.
 Print out each object. Note that you won’t get any information about the boundary or maximum number of
steps (think about what your toString method does), but that’s ok.

Compile and run the program to make sure everything is correct so far.
3. Next add the following method to the RandomWalk class: void takeStep(). This method simulates taking a single
step either up, down, left, or right. To “take a step” generate a random number with 4 values (say 0, 1,2, 3) then use
a switch statement to change the position (one random value will represent going right, one left, and so on). Your
method should also increment the number of steps taken.
4. Add a for loop to TestWalk.java to have each of your RandomWalk objects take 5 steps. Print out each object after
each step so you can see what is going on. Compile and run the program to make sure it is correct so far.
5. Now add to RandomWalk.java the following two methods. Each should be a single return statement that returns the
value of a boolean expression.
 boolean moreSteps() - returns true if the number of steps taken is less than the maximum number; returns
false otherwise

118 Chapter 7: Object-Oriented Design


 boolean inBounds() - returns true if the current position is on the square (include the boundary as part of the
square); returns false otherwise.
6. Add to the RandomWalk class a method named walk that has no parameters and returns nothing. Its job is to
simulate a complete random walk. That is, it should generate a sequence of steps as long the maximum number of
steps has not been taken and it is still in bounds (inside the square). This should be a very simple loop (while or do...
while) --- you will need to call the methods takeStep, moreSteps, and inBounds.
7. Add to TestWalk.java a statement to instantiate a RandomWalk object with a boundary of 10 and 200 as the
maximum number of steps. (You may want to comment out most of the code currently in TestWalk -- especially the
user input and the loop that takes five steps -- as the walk method will be easier to test on its own. The /* ... */ style
of comment is useful for this. But don’t delete that other code, as you’ll need it later in the lab.) Then add a statement
to have the object walk. Print the object after the walk. Compile and run the program. Run it more than once -- you
should be able to tell by the value printed whether the object went out of bounds or whether it stopped because it
reached the maximum number of steps.
8. Now write a client program in a file named DrunkenWalk.java. The program should simulate a drunk staggering
randomly on some sort of platform (imagine a square dock in the middle of a lake). The goal of the program is to
have the program simulate the walk many times (because of randomness each walk is different) and count the
number of times the drunk falls off the platform (goes out of bounds). Your program should read in the boundary,
the maximum number of steps, and the number of drunks to simulate. It should then have a loop (a for loop would
be a good idea) that on each iteration instantiates a new RandomWalk object to represent a drunk, has the object
walk, then determines whether or not the drunk fell off the platform (and updates a counter if it did). After the loop
print out the number of times the drunk fell off. Compile and run your program. To see the “randomness” you
should run it several times. Try input of 10 for the boundary and 200 for the number of steps first (sometimes the
drunk falls off, sometimes not); try 10 for the boundary and 500 for the steps (you should see different behavior); try
50 for the boundary and 200 for the steps (again different behavior).
9. Now write a second client program in a file named Collisions.java. This program should simulate two particles
moving in space. Its goal is to determine the number of times the two particles collide (occupy exactly the same
position after the same number of steps -- the steps could be thought of as simulating time). We’ll assume the
particles are in a very large space so use a large number for the boundary (such as 2,000,000). Use 100,000 for the
maximum number of steps. (Don’t enter the commas.) Start one particle at (-3, 0) and the other at (3, 0). (You can
hardcode these values into the program; no need to enter them.) Your program should contain a loop that has each
particle take a step as long as the particles have not exceeded the maximum number of steps. The program then
determines how often the particles have collided. Note that in order for your program to know whether or not the
two different RandomWalk objects are in the same place it needs to be able to find out the position. Hence, you need
to add the following two methods to the RandomWalk class.
 int getX() - returns the x coordinate of the current position
 int getY() - returns the y coordinate of the current position

Compile and run your program to make sure it works. As before run it several times.
10. In your Collisions.java program the condition to determine if the points are at the same position is a bit cumbersome.
This is something that would be best put in a separate method. Add a static method to Collisions.java (after the main
method) with signature

public static boolean samePosition (RandomWalk p 1, RandomWalk p2)

The method should return true if p1 and p2 are at the same position and return false otherwise. Modify your main
method so it calls samePosition rather than directly testing to see if the objects are at the same position. Test the
program.

11. In using random walks to simulate behavior it is often of interest to know how far away from the origin the object
gets as it moves.

Chapter 7: Object-Oriented Design 119


a. Add an instance variable maxDistance (type int) to the RandomWalk class. This should be set to 0 in each
constructor.
b. Now the takeStep method needs to update this maximum when a step is taken. We’ll add a support method
to the class to do this. Add a private method named max that takes two integer parameters (say num1 and
num2) and returns the largest of the two.
c. Add code to takeStep to update maxDistance. This can be done in a single statement using the max method
-- the new value of maxDistance should be the maximum of 1) the old value of maxDistance, and 2) the
current distance to the origin. Note that if the current point is (-3, 15) the distance to the origin is 15; if the
current point is (-10, 7) the distance to the origin is 10. Remember that Math.abs returns the absolute value
of a number.
d. Finally add an accessor method to return that distance so a client program can access it:
public int getMaxDistance()
e. Test the maximum by adding statements in TestWalk.java to get and print the maximum distance for each
of the objects after the loop that had them take and print out 5 steps (this way you can see if the maximum
is correct - each step is printed).

// ************************************************************
// TestWalk.java
//
// Program to test methods in the RandomWalk class.
// ************************************************************

import java.util.Scanner;

public class TestWalk


{
public static void main (String[] args)
{
int maxSteps; // maximum number of steps in a walk
int maxCoord; // the maximum x and y coordinate
int x, y; // starting x and y coordinates for a walk

Scanner scan = new Scanner(System.in);

System.out.println ("\nRandom Walk Test Program");


System.out.println ();

System.out.print ("Enter the boundary for the square: ");


maxCoord = scan.nextInt();

System.out.print ("Enter the maximum number of steps: ");


maxSteps = scan.nextInt();

System.out.print ("Enter the starting x and y coordinates with " +


"a space between: ");
x = scan.nextInt();
y = scan.nextInt();
}
}

120 Chapter 7: Object-Oriented Design


Telephone Keypad
Files Telephone.java and TelephonePanel.java contain the skeleton for a program to lay out a GUI that looks like telephone
keypad with a title that says “Your Telephone!!”. Save these files to your directory. Telephone.java is complete, but
TelephonePanel.java is not.

1. Using the comments as a guide, add code to TelephonePanel.java to create the GUI. Some things to consider:
a. TelephonePanel (the current object, which is a JPanel) should get a BorderLayout to make it easy to
separate the title from the keypad. The title will go in the north area and the keypad will go in the center
area. The other areas will be unused.
b. You can create a JLabel containing the title and add it directly to the north section of the TelephonePanel.
However, to put the keypad in the center you will first need to create a new JPanel and add the keys (each a
button) to it, then add it to the center of the TelephonePanel. This new panel should have a 4×3 GridLayout.
c. Your keypad should hold buttons containing 1 2 3, 4 5 6, 7 8 9, * 0 # in the four rows respectively. So
you’ll create a total of 12 buttons.

2. Compile and run Telephone.java. You should get a small keypad and title. Grow the window (just drag the corner) and
see how the GUI changes - everything grows proportionately.

3. Note that the title is not centered, but it would look nicer if it were. One way to do this is to create a new JPanel, add the
title label to it, then add the new JPanel to the north area of the TelephonePanel (instead of adding the label directly).
This works because the default layout for a JPanel is a centered FlowLayout, and the JPanel itself will expand to fill the
whole north area. Modify your program in this way so that the title is centered.

//************************************************************
// Telephone.java
//
// Uses the TelephonePanel class to create a (functionless) GUI
// like a telephone keypad with a title.
// Illustrates use of BorderLayout and GridLayout.
//************************************************************
import javax.swing.*;
public class Telephone
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Telephone");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TelephonePanel());
frame.pack();
frame.setVisible(true);
}
}

Chapter 7: Object-Oriented Design 121


//************************************************************
// TelephonePanel.java
//
// Lays out a (functionless) GUI like a telephone keypad with a title.
// Illustrates use of BorderLayout and GridLayout.
//************************************************************
import java.awt.*;
import javax.swing.*;

public class TelephonePanel extends JPanel


{
public TelephonePanel()
{
//set BorderLayout for this panel
//create a JLabel with "Your Telephone" title
//add title label to north of this panel
//create panel to hold keypad and give it a 4x3 GridLayout
//add buttons representing keys to key panel
//add key panel to center of this panel
}
}

122 Chapter 7: Object-Oriented Design


Random documents with unrelated
content Scribd suggests to you:
Bellaert, the early printers of Haarlem, should have heard
from Cornelis this story about Coster and his invention.
The people of Haarlem, we are told, were proud of
Coster, and envious of the honors conceded to
Gutenberg. Why the printers and the people of Haarlem
allowed the important testimony of Cornelis to remain
unpublished for so long a time is a question that cannot
be answered.
At this late day, it is impossible to discover the kernel of
truth that may be concealed in the heart of so great a
husk of fiction. It may be that Cornelis, who seems to
have been a simple-minded man, and who appears as a
binder in the church record about nine years before
Bellaert opened his printing office, imagined that this first
printing office in Haarlem was the first printing office on
the globe. There may have been a theft of types and of
secrets from the office of Jacob Bellaert at or about 1485.
Cornelis blundered about dates, and his inaccuracies have
been exaggerated by the gossip of the next generation.
These are possible conjectures. p345 But we must
remember that this story of Cornelis is not told by
himself, but by Junius.
One of the authorities referred to by Junius is Talesius,
burgomaster of Haarlem when Junius was writing
Batavia . In referring to him, Junius is careful in his choice
of words. “My account does not disagree with that of
Talesius. . . . I recollect that I have heard from him nearly
the same story.” This is a timid assertion—one that
Talesius could have modified in some of its features.
Talesius himself has not spoken. Talesius was, in his
youth, the secretary, and, in mature age, the intimate
friend of Erasmus, to whom he must have spoken about
the legend, but he did not make Erasmus believe it.201
The mysterious disappearance of the practice of the art
from Haarlem is even more wonderful than its
introduction. The tools may have been stolen, but the
knowledge of the art must have remained. Coster may
have died immediately after the theft, but his son-in-law
Thomas Pieterzoon, and the workmen, who knew all
about the details of typography, were living, and able to
go on with the work.202 The making of books may have
been temporarily suspended, but the curious p346 public
who clamored for them should have persuaded Coster’s
successors to fill their wants. The new art of printing
which found so many admirers should not have been
completely forgotten fifty years afterward. There is
nothing in the story of Junius to satisfy these doubts. If
we accept his account of the invention, we must rest
contented with the belief that typography in Haarlem died
as suddenly as it was born, leaving behind as its only
relics one edition of the Speculum and the old wine-
flagons of Thomaszoon. The same strange fatality
followed the alleged thief John who fled to Mentz and
printed two books in 1442. Immediately after, his types,
his peculiar process and his printed books disappear
forever.
The improbable features of this legend were not seen
in the uncritical age in which Batavia was written.
Patriotic Dutchmen did not wish to see them. Holland, at
the close of the sixteenth century, was flushed with pride
at her successful resistance to the power of Spain.
Grateful to the men who had made her famous, she
exaggerated the services of all her eminent sons. Coster
was not forgotten. The name of Junius gave authority to
the Haarlem legend, and the story of Coster was read
and believed throughout the Netherlands. There were
dramatic features connected with it which pleased the
imagination and fastened themselves to the memory. To
people who had no opportunity to examine the
evidences, the legend of Haarlem soon became an article
of national faith, to disbelieve which was to be disloyal
and unpatriotic. But this enthusiasm would have subsided
if it had not been nourished. If subsequent writers had
added nothing to this legend of Junius, it would not be
necessary to write more about it. Long ago it would have
been put aside as untrue. But the legend has grown: it
has been almost hidden under the additions that have
been made to it. The snow-ball has become a snow-heap.
It is necessary to expose the falsity of the additions as
well as of the legend, and to show how recklessly this
chapter of the history of typography has been written.
XVIII

Perversion by Bertius . . . Romance of Scriverius . . . Date of Invention


removed to 1428 . . . Illustration of First Statue to Coster . . . Date of 1420
given by Boxhorn . . . Rooman’s Date of 1430 . . . History and Chronology
of Seiz . . . Doubts of Hollanders . . . Discrepancies in the Dates on Medals
. . . Meerman and his Unsatisfactory System . . . Fac-similes of Medals . . .
Koning and his Prize Essay . . . Dr. De Vries’s Theory . . . Radical
Disagreements of the Authors . . . All Versions Enlargements of the Legend
as given by Junius . . . An Article of Patriotic Faith in Holland . . .
Monuments to Coster . . . Illustration of Last Statue.

AT the end of the sixteenth century, the legend had two


strong supports—the authority of an eminent scholar, and
the patriotic pride of the Hollanders, who accepted it as
truthful history. It did not, however, pass the ordeal of
criticism unharmed: the weaker points of the legend were
exposed by many German authors, and the weight of
their objections compelled Dutch writers to attempt new
explanations. Bertius,203 writing in 1600, and evidently
perplexed by the carelessness with which Junius had
noticed Coster’s first experiments, says, but without
producing any proof, that “Coster invented the art of
printing with engraved blocks or xylography . . . . the
three-fold villain John Faust stole the invention.” Here we
see the unavoidable result of Junius’s p348 malignant
innuendo: Bertius does not hesitate, as Junius did, to
name Fust as the false workman who stole Coster’s tools.
Peter Scriverius thought it necessary, in 1628, to
enlarge and embellish the story of Junius. He wrote a
new version of the invention, which appeared with a
curious poem called the Laurecrans .204 This, says
Scriverius, was the manner of it: In the year 1428,
Laurens Coster, then a sheriff of Haarlem, strolled in the
Haarlem wood. He took up the branch of an oak-tree, cut
a few letters in relief on the wood, and after a while
wrapped them up in paper. He then fell asleep, but while
he slept, rain descended and soaked the paper.
Awakened by a clap of thunder, he took up the sheet,
and, to his astonishment, discovered that the rain had
transferred to it the impress of the letters. Here was the
suggestion of xylography, which he at once followed to a
successful conclusion. He printed a great many block-
books and a Donatus , but finding to his surprise that
letters cut upon a solid block could not be used for other
work, he thereupon invented typography. John
Gutenberg, who had been employed as a workman, stole
the tools and the secret. Disheartened with this
misfortune, Coster abandoned printing and died. He
proceeds:
It is my opinion that the art was first invented ten or twelve years
before the year of our Lord 1440 (in which the most trustworthy
authors agree), in Holland, at Haarlem. Junius has told its beginning
and progress before us. And although he discovered some particulars
about the invention, yet he has (I may be allowed to say it without
disturbing his ashes) his errors, and may not be pronounced free
from inadvertence. To-day (A. D. 1628) is just two centuries since the
p349 excellent and valuable art of printing made its appearance (A. D.
1428). Not in the manner that is used now, with letters cast of lead
and tin. No, it did not go on like that; but a book was cut, leaf for
leaf, on wooden blocks . . . . We must not think that every letter was
cut separately on wood, and that these letters were collected and put
together to a line, and in a certain number of lines. . . . . Our acute
Laurens first cut the letters, twisted and close to each other, in the
manner of writing on wood or tin; but afterward, when he was so
successful, he changed his method of working, and, having invented
the matrices, cast his letters. (!)
I will not say further how the noble art of engraving and printing of
engravings is connected with the invention of printing, which arose
afterward. But just as the dexterous Jan Fuyst imitated the
appropriate art of printing, so the excellent and talented printers and
designers, who also handled the artistic chisel and knife, contrived to
multiply and publish their engravings, cut after the printing of the
Haarlem figures. And all have been instructed by, and got their first
experience from, our clever and talented Laurens Koster.205
Scriverius has given dates and new details, but he has
not thrown any clear light on the subject. He has not
made the story of Junius more credible, but he has
exposed himself as a romancer and a fabricator. In trying
to mend the legend, he has destroyed it. If the story of
Scriverius is true, then that of Junius is false, for they
contradict each other. The statements of Junius were
based on the pedigree and the gossip of the old men of
Haarlem; the statements of Scriverius were based on
nothing, for he had no authorities which the most lenient
critic could accept.
Scriverius said that Lourens Janszoen or Laurens Koster
was the inventor of xylography as well as of types. After
an examination of the Speculum , he had wit enough to
see what Junius did not, that the printer of the book must
have had practice with blocks, and that printing on blocks
necessarily preceded printing with types. His description
of the growth of the new art is not at all satisfactory. The
careless manner in which he skips over the invention of
matrices and the making of the moulds is that of a man
who knows nothing p350 about type-founding, neither
from instruction nor observation. Encouraged by the
praise which Scriverius had received for his performance,
Marcus Zuerius Boxhorn undertook to place the date of
the invention eight years earlier. In his Dissertation on the
Invention of Typography , printed by Vogel at Leyden in
the year 1640,206 Boxhorn says that the invention was
made in 1420. Here we encounter a curious fact. The
story of Junius had been published less than fifty years,
yet the writers disagreed concerning the date of the
invention. Believers in the legend had been taught by one
teacher that typography was invented in 1440—by
another, in 1428—by another, in 1420. And it is a
noticeable circumstance that the authors farthest
removed from the date of the invention were the most
positive in their statements. The later writers, who knew
the least, give us the earlier dates.
Adrien Rooman, a printer of Haarlem, and apparently a
conservative and conciliatory man, thought that these
differences could be most satisfactorily adjusted by fixing
the date midway between the extremes. He was not in
the possession of any newly discovered facts, and had no
authority for the arbitrary selection, but this
incompetency did not prevent him from publishing a
portrait of Coster, with an inscription which made the year
1430 the date of the invention.
To the thinking men of Haarlem the assumptions of
Boxhorn were as unsatisfactory as those of Junius and
Scriverius. There was an air of improbability, or at least of
uncertainty, about the statements of all the authorities,
which filled their minds with doubts as to the truth of the
legend. The statue to Coster, which was soon after put up
in the Doctors’ Garden, had no date of invention on the
pedestal. To remove these doubts, Seiz207 undertook, in
1742, to furnish “a true and rational account of the
invention” by Coster. The truth and reason of this new
description of the invention of Coster are most strikingly
illustrated in its chronology. p352
The Statue of Coster in the Doctors’ Garden. ♠
[From Seiz.]
see larger
1428 Laurens Coster engraved a few letters upon the bark of a
tree.
1429 He gave one year to experimental engraving on wood.
1431 He printed the Temptations of Demons or Ars Moriendi .
1432 Printed the Bible of the Poor .
1435 He began to engrave and print an edition of the Donatus .
1436 He cut separate letters or single types out of lead.
1437 After prolonged experiment, he abandoned this method.
1438 He invented a method of casting types of lead.
1439 He began to print an edition of the Donatus , and the
Dutch edition of the Speculum . In this year Gutenberg
took service with Coster, and began to print for him, by
which he earned the title of the Book-printer of
Haarlem. (!)
1440 Gutenberg absconded with some knowledge of the
invention. He was able to cut, but not to cast types. (!)
1441 He established a printing office in Mentz.
1442 Gutenberg printed an A b c book, the Doctrinal of
Alexander Gallus and the Treatise of Peter of Spain. By
this time Coster had repaired the damages of the theft.
1443 Coster printed the second edition of the Speculum in
Dutch.
1444 Coster printed a Latin edition of the Speculum .
1446 Gutenberg also induced Gensfleisch, called afterward
Faust, (!) and Meydenbach to join him in printing a
Latin Bible .
1457 Coster’s art was well known, and excited the envy of the
Archbishop of Canterbury and of King Henry VI of
England.
1457 The Archbishop persuaded the king to get a knowledge of
the art from Gutenberg, the first book printer of
Haarlem. (!)
1459 Turnour and Caxton, who were sent on this mission, bribed
Frederick Corsellis, a workman of Coster, to run away
from Haarlem in disguise. To prevent his escape,
Corsellis was taken to Oxford, in which town he began
to print in 1468.
1467 Coster died, about the same time that Gutenberg and
Faust died. (!) His printing office ceased to exist.208
Seiz has not told us where he obtained this curious
information, but we shall make no mistake if we attribute
it to an imagination disordered by national pride. His
chronology is so absurd that serious criticism would be a
waste of time.
Notwithstanding the strong efforts of Seiz to remove
the impression created by the contradictory accounts of
his predecessors, the citizens of Haarlem seemed to be
involved in p353 greater doubts than ever about the
chronology of the invention. For, in 1740, upon the
occasion of the third jubilee of Coster’s invention, two
silver medals were struck, with legends curiously unlike.
We here see that the name of the inventor is printed in
different forms; one medal bears the date 1440, and the
other contains the date 1428. These irregularities prepare
us for what is to follow.
Medals in Honor of Coster. ♠
[From Seiz.]

In 1757, Gerard Meerman, subsequently a


distinguished champion of the Haarlem legend, wrote
“that the pretentious assertion of the invention of printing
by Laurens Coster begins to lose credit more and more.
The particulars that have been related by Seiz are mere
suppositions, and the chronology of Coster’s invention
and enterprise is a romantic fiction.”
But, in the year 1760, Daniel Schoepflin, an eminent
scholar of Strasburg, wrote a valuable contribution to the
history of typography, under the title of Vindiciæ
Typographicæ . Meerman was provoked to emulation. He
had not believed in the legend, but he thought that he
could construct a theory of the invention, which would, to
some extent, concede the claims of the rival cities of
Haarlem, Strasburg and Mentz. In this illogical manner, by
the construction of a theory before p354 he was in
possession of the facts, he began to write the Origines
Typographicæ . The entire book was published in 1765,
with a portrait of Lourens Coster by the eminent Dutch
engraver Houbraken, and a portrait of Meerman himself
by Daullé. In the matter of scholarship, Meerman was
thoroughly qualified for his task. He wrote in a clear style
and with admirable method. But he knew nothing of the
mechanics of printing nor of type-founding, and,
unfortunately, he was too conceited to accept correction
or instruction even from the hands of experts like
Enschedé, Fournier and others. In trying to make facts
suit theories, he went so far as to order the engraver of a
fac-simile to stretch the vellum of a Donatus so that the
types used upon this Donatus should appear to be the
same as the types of the Speculum .
Medals in Honor of Coster. ♠
[From Seiz.]

These are the conclusions submitted by Meerman as


the result of his study of, and reflection on, the legend of
Haarlem:
Typography was invented by Louwerijs Janszoen, also known as
Laurens Coster, who, at various times between 1422 and 1434, filled
the office of sheriff, treasurer and sacristan. He was of noble blood,
but a bastard of one of the p355 Brederodes. He died sometime
between 1434 and 1440. He invented typography about 1428 or
1430, using only movable types of wood. All that Junius has written
about an invention of lead and tin types by Coster is incorrect. He
thinks it useless to consider the engraving of letters upon solid wood-
blocks, for this is not typography, and is not printing as we now
understand it. Laurens was robbed on Christmas night, 1440, by
Johan Gensfleisch the elder, who carried the art to Mentz. The son-
in-law and heirs of Coster continued his business for some time after
his death, but with little appreciation, as they were overshadowed by
the superior invention of Gutenberg and Schœffer. Coster printed but
one edition of the Speculum from types of wood. His successors
printed the other Dutch edition and the two Latin editions from
engraved metal types. The contributions of different inventors toward
the perfect invention are acknowledged in this manner: Laurens
Coster was the first to demonstrate the feasibility of typography by
his use of wood types; John Gensfleisch was the first to make cut or
engraved metal types; Peter Schoeffer was the inventor of cast or
founded metal types; John Gutenberg and John Fust were printers
who invented nothing.
Meerman had fair warning from the type-founder and
printer John Enschedé that his theories of wood types209
and of cut metal types were preposterous. He did not
heed the warning. He wrote, not for printers, but for
bibliographers who believed in the practicability of wood
types, and he did not mistake his readers. The
bibliographers, who knew little or nothing of the theory or
practice of type-making, were not competent to criticise
the mechanical part of his theory. He hoped to disarm the
prejudices of German authors by his frank
acknowledgment of the contributions of Schœffer and
Gensfleisch as co-inventors. The novelty of his theory, the
p356 judicial equity with which he decreed to Coster,
Gensfleisch and Schœffer what he said was their share in
the honors of the invention, the temperate tone and calm
philosophic spirit in which the book was written, the
breadth of scholarship displayed in exact quotations from
a great number of authors, won admirers in all countries.
The theory of Meerman about a contributive invention
need not be examined here: it has been entirely refuted
by many French and German authors; it was abandoned
even by Hollanders210 at the beginning of the present
century. The authority of the book is at an end.
The conviction that all previously written defences of
the legend were untenable, caused a scientific society of
Holland to offer a prize for the best treatise on the
invention. Jacobus Koning was the successful competitor.
In 1816, he published, under the sanction of the society,
the essay that had won the prize, under the title of “The
Origin, Invention and Development of Printing .” It was an
inquiry of more than ordinary merit—the first book on the
subject which showed evidences of original research.
Koning tried to supplement the many deficiencies of
Junius, with extracts from the records of the old church
and town of Haarlem, which he had studied with
diligence. He brought to light a great deal of information
about one Laurens Janszoon, whom he confounded, as
Meerman had done, with Lourens Janszoon Coster. This is
the substance of his discoveries and of his conclusions
therefrom:
Koning describes the inventor as Laurens Janszoon Koster, and not
as Lourens Janszoon. He says that Koster was born about 1370; that
there are no records of his early life, and that his name does not
appear on any of the registers of Haarlem, municipal or ecclesiastical,
until he became a man of middle age. After this period of his life,
notices are frequent. He was the sacristan of a church from 1421 to
1433. He was, at different times, alderman and presiding alderman,
treasurer of the town, lender of money to the city, officer in the
citizens’ guard, member of the grand council, and deputy to a p357
convocation of the States—clearly a man of wealth and distinction.
There was a great pestilence in Haarlem in the latter part of the year
1439, and Koning says it seems probable that Koster was one of its
many victims. Koster’s only child was a daughter named Lucette, who
married Thomas, the son of Pieter Pieterzoon—the Peter mentioned
by Junius. Pieterzoon had three children, but with them the family
name was lost. This Laurens Janszoon Koster invented xylography
and typography. He experimented with types of wood, but did not
use them for practical work. His types were founded in matrices of
lead, and in moulds of metal; he invented printing ink, and printed
his books with inking balls on a press. His materials were rude, but
the process was substantially the same as that of modern printers.
He printed the first edition of the Speculum in 1430, and sixteen
other books before his death. His business as a printer was continued
for some years, but in a feeble manner, by his grandsons. The thief
of Koster’s process was Frielo Gensfleisch.
In the town records Koster is not noticed as a printer,
but Koning described his method of printing, his punches,
moulds, matrices, presses, inking balls, ink, types, and
printing office furniture, with as much boldness as if he
had been eye-witness to the entire process. Nor was this
his only error. It has since been proved that he willfully
suppressed many important facts in the records which are
of great importance in an examination of the life and
services of Coster. It is plain that he was more intent on
pleasing the national pride than on revealing the truth.
The speculations of Koning were destroyed by the keen
criticisms of the authors who followed him. Dr. Abraham
De Vries211 set aside impatiently nearly all the ingenious
theories devised by former commentators. He repudiated
the statement that Coster had been a sexton or sacristan,
or that he invented engraving on wood. Warned by the
failures of his predecessors, he advanced no new theory
about the peculiarities of Coster’s typographic process; he
professed to be satisfied with the bald statement of
Junius, and dogmatically maintained that Coster “was the
inventor of typography, of the proper art of printing, the
first who invented and practised p358 the art of printing
with movable and cast letters, and so gave the example
to Mentz. . . . In the beginning, the art was secretly
practised as a trade in manuscripts, not only during the
lifetime of the inventor, but by his successors after his
death.” De Vries placed the invention about 1423.
It is not necessary to protract this review of the
different versions of the legend, nor yet to point out the
fatal disagreements and inaccuracies of these versions. It
is plain that all the authors who have maintained the
claims of Coster have taken their leading facts from
Junius. It is equally plain that they have been dissatisfied
with his statements and have tried to fill up the gaps in
the evidence with conjectures. But they have not made
the legend any more credible. The exact nature and date
of the invention, the name of the inventor, his method of
making types, the books he printed, the thief who stole
his process, the fate of his printing office, the total
disappearance of the knowledge of the new art—these
and other features of the positive statement first made by
Junius are enveloped in as complete a mystery as they
were when Batavia was written.
With all its inconsistencies and improbabilities, the
legend has been accepted as essentially truthful by many
eminent bibliographers in France and England. Of late
years it has encountered but feeble opposition from
German writers. In many modern books on printing,
Coster has been recognized either as the inventor or as
one of the co-inventors of the art. There has been a
general belief that, however absurd the legend might be
in some minor matters of detail, it had a nucleus of truth.
Coster’s place in typographical history, at the middle of
the present century, seemed almost as firmly fixed as
that of Gutenberg.
In Holland, this legend of the
invention of printing by Coster
was an article of national faith
which only the bold man dared to
deny. It has produced results
which could never have been
fore­seen by the vain old man
Gerrit Thomas­zoon, in whose
conceit the fable orig­inat­ed.
Haarlem is dotted with p359 mon­‐
u­ments to the memory of Coster.
Certain days in June and July are
observed as festivals in com­‐
mem­ora­tion of the invention. In
the Hout, or Haarlem Wood,
where Coster is said to have
received his first sug­ges­tion of
types, an imposing cenotaph has
been placed. Carved on this
stone are the arms of the sheriff
Laurens Jans­zoon, and the year
The Statue on the New ♠
1423, which is offered as the Monument to Coster.
[From Noordziek.]
date of this sug­ges­tion. An ack­‐
now­ledg­ment of Coster as the inventor of typ­og­raphy
may be seen in the ancient cath­ed­ral of Haarlem, on a
black marble tablet, which was put in place during the
month of June, 1824, by King William I. In almost every
well appointed public office or private house of Haar­lem is
some pic­torial recog­ni­tion of Coster as the in­ven­tor of
print­ing.
In the year 1851, an as­so­cia­tion of patriotic Hol­landers
placed in front of the rebuilt Coster house a memorial
stone with this inscription: “The house of Coster: the
birthplace of typography.” The date of this birth is
judiciously omitted. The tablet of the old Coster house
contained an inscription in honor of “Laurens Coster,
sheriff, of Haarlem, inventor of typography about the year
1430.” The vitality of the legend has also been preserved
by the issue of a great many medals, prints and papers,
and by the repeated assertion of the civic authorities that
Coster was the original and unquestionable inventor of
typography.
XIX

The Vague Inscription on the Last Monument . . . Relics in the Costerian


Museum . . . Fac-simile of Janszoon’s Autograph . . . The Coster Pedigree
. . . Made by Gerrit Thomaszoon . . . Legend began with the Pedigree . . .
Pedigree has been Falsified, and is of No Authority . . . Search by Van der
Linde for Records concerning Coster . . . Archives of the Town and Church
of Haarlem represent Coster as a Tallow-Chandler and Innkeeper . . .
Coster living at Haarlem in 1483 . . . The Record of the Chair-Book . . . No
Evidence that Coster was a Printer . . . Lourens Coster has been
Confounded with Laurens Janszoon . . . Illustration of the House of Coster
. . . Other Fac-similes of Portraits of Coster . . . Their Curious Dissimilarity
. . . Absurdity of the Legend.

IN the year 1856, on the sixteenth day of July, the day


accepted as the anniversary of the invention, a statue of
Coster was put up in Haarlem. The tablets of the pedestal
bear inscriptions which are thus translated by Hessels:

The date of the invention and the profession or position


of the inventor are omitted. We cannot ascertain from the
monument whether Coster was a sheriff or a sexton,
whether he invented printing in 1423 or 1440. It may be
inferred that there had been disagreements among the
eminent men who erected this work of patriotism, and
that they could not p361 heartily accept the date of any
version of the legend. On this great occasion the
Costerian Museum212 of Haarlem was enriched with a
pedigree of the Thomaszoon family, an old document
frequently referred to by some defenders of the legend as
an incontestable evidence of its truth. The pedigree was,
without doubt, a genuine relic. Its dingy vellum surface,
written over in many handwritings, was surrounded by an
embroidered border blackened with age. Its history could
be traced through three centuries. Gerrit Thomaszoon,
the aged descendant of Coster mentioned by Junius with
such marked respect, was the person by or for whom this
pedigree was made in or about the year 1550.213 This
Gerrit Thomaszoon had kept an inn in the house once
occupied by Coster, and it is supposed that the pedigree
was one of the decorations of a wall in his house. There
is a special significance in this date of 1550.

Autograph of Laurens Janszoon. ♠


[From Koning.]

This pedigree, which describes Coster as the inventor


of printing, was written at least one hundred years after
the discovery of the invention and the death of the
inventor. It was written when Cornelis, the only eye-
witness known to p362 history, had been dead nearly
thirty years. It is, however, and too much stress cannot
be laid on this fact, the oldest document in which
mention is made of Coster as a printer. There are valid
reasons for the belief that Coster’s merit as an inventor
had never been recognized in any way before the record
was made on this pedigree. When we consider the order
of the dates, it is obvious that it was from this much
suspected document that Coornhert derived the
information he published in 1561. “The old, dignified and
grey heads” described by Van Zuren in 1561, “the aged
and respectable citizens” of Guicciardini (1566) and
Junius (1568), were Gerrit Thomaszoon and his friends,
among whom we may properly include Gallius and
Talesius. And it may be added that the more
circumstantial story of Junius was first published when
Gallius and Talesius were dead, and when there was no
man living who could controvert or modify any part of his
story.
There can be no doubt that the legend began with this
pedigree. It is not at all probable that the vain old man
Gerrit Thomaszoon, who was proud of the ancestor in
whose house he lived, kept his friends in ignorance of it.
It was not unknown to Junius. There is a similarity of
uncertainty between an ambiguous date (1440 or 1446)
on this pedigree and the mysterious circumlocution of
Junius in his use of the words “about one hundred and
twenty-eight years ago,” or 1440, which is enough to
show that Junius had not only seen the pedigree, but that
he took it as an authority for this date. Whether
Scriverius saw it cannot be confidently maintained; he
does not mention it. Gerard Meerman knew of its
existence, but he did not reprint it. He made use of it,
however, in the construction of a new genealogy of the
Coster family, in which he added and altered items in the
most unwarrantable manner. Koning studied it with
diligence: he frequently alluded to it as a document of the
highest importance, but he did not reprint it, nor even
describe it in general terms.
The withholding of this pedigree from public
examination, and the evasion of its description by the
authors who had p363 examined it, are suspicious
circumstances. We see that men who wrote hundreds of
pages of speculations to support the claims of Coster—
men who translated and reprinted many columns of
irrelevant chaff for the sake of one little kernel of grain—
willfully suppressed what they maintained was a most
convincing evidence of the truth of the legend. It was not
suppressed because it was too long: the entire pedigree
can be printed in two pages.
The reasons for withholding the pedigree were
apparent when it was put in the Museum. The reading of
the words in the first row at once produced the
impression that its importance had been vastly overrated;
that its information was of little value; that it was almost
worthless as evidence of the priority of Dutch typography.
Dr. Van der Linde, who made a critical examination of the
writing soon after it was placed in the Museum, revealed
the astonishing fact that the most important entry had
been falsified. This entry, which contains the only portion
of any interest in an inquiry concerning the invention of
printing by Coster, consists of the following lines:
“Sijn tweede wijff was “His [Thomas Pie­ter­zoon’s] se­‐
Lourens Jans­soens cond wife was Lourens Jans­‐
Cos­ters doch­ter die soen’s Cos­ter’s daugh­ter who
deerste print in die brought the first print in the
werlt brocht Anno world in the year 1446.”
1446.”
The date first written was 1446, but in this column, and
in others, objectionable entries have been effaced and
falsifications have been attempted. The figure 6 has been
partially rubbed out; it has been replaced by a 0, so that
the careless reader will construe the date as 1440. There
can be no hesitation whatever on this point; the figures
first written surely were 1446. “We see here a fable arise
before our very eyes. A Haarlem citizen has a pedigree
made for him, probably to put it up in his inn. . . . . . But
the frame wants lustre, and so the pedigree is linked by
the probably totally fictitious Lucye, the second wife, to a
Haarlemer—to a Haarlemer who (the awkwardness and
naïveté of the expression may not surprise p364 us at all
in such a product of family vanity) brought the first print
in the world.”214
We may waive all criticism of the faulty grammar of the
pedigree and proceed to more important matters. It may
be conceded that the pedigree was written by an ignorant
man who intended to say that it was Coster, and not his
daughter, who brought the first print in the world. By the
word print Thomaszoon may have meant a playing card,
the engraved figure of a saint, a block-book, or a book
made from movable types. If he meant any product of
xylographic printing, the statement is totally false, and
deserves no consideration. If he meant typography, his
failure to express that meaning is unfortunate. But his
intention is really of but little importance. A bald
statement on a pedigree, written by an ignorant and
conceited man, about one hundred years after the great
event he professed to record, of the details of which he
obviously knew nothing, cannot be used to overthrow
established facts in the history of typography.
It is unsatisfactory in other points. The alteration of the
date, and the unexplained erasures have destroyed
whatever validity the document may have had. It may be
put aside; as an authority it is worthless. Its obscure
notice of the invention of printing is but a frail foundation
for the colossal superstructure which Junius erected. It is
plain that Junius must have been conscious of its
weakness as a basis for the legend; he had doubts of its
accuracy, and dared not refer to it. He preferred the oral
testimony of the dead Cornelis.
The discovery of this falsification induced Dr. Van der
Linde to make, “with a zeal and patience worthy of a
better cause and of a better reward,” a laborious
investigation in the archives of the town and church of
Haarlem for authentic p365 information concerning Coster.
He had cause to think that history had been falsified by
other historians of the legend. Through the study of the
archives, Van der Linde ascertained that there lived in
Haarlem, in the fifteenth century, a citizen whose name
was Lourens Janszoon Coster, the son of one Jan Coster
who died in 1436. The results of the search were as
curious as they were unexpected, as will be fully
understood after an examination of this translation of the
originals:
1441 On the evening of the 13th, settled with lou koster
for 15 pounds and 12 pounds of oil, each pound
an ancient but­drager, and 34 pence for soap and
tallow candles, together 22 guilders 3 pence.
1441 Louwerijs Jans­soen, for 72 pounds of candles, which
have been burnt by the guards in the town hall
during the year—for each pound an ancient but­‐
drager.
1441 Louwerijs Jans, afore­said, for the candles burnt in
the tower in honor of Our Lady, during this year,
as was agreed with him.
1442 Lourijs Coster, paid for having repaired the lantern of
Our Lady in the tower.
1442 Lourijs Coster, for 40 pounds of tallow candles which
the guards in the town hall burnt; cost each
pound an ancient but­drager.
1442 Paid to lou coster 8 guilders for oil and soap.
1442 To lou coster for soap, candles and other things, 15
pence.
1447 On the 14th day of March, paid to Louwerijs Coster
for 5 pounds of candles burnt in the tower in
honor of Our Lady.
There can be no mistake about the business of this
man. The Lourens Janszoon Coster described on the old
pedigree as the famous man who brought the first print
in the world, and in Batavia as a wealthy citizen, a man
of leisure and of enlarged mind, and the inventor of
engraving on wood and typography, was certainly an
obscure tallow-chandler, who sold oil and candles.215 The
anti-climax is sufficiently absurd, but worse remains. The
archives give us more than a clue to the origin of Coster’s
wine-flagons. It seems that, some time p366 after 1447,
this Lourens Janszoon Coster gave up the business of
chandler in favor of his sister Ghertruit Jan
Costersdochter, and that he chose for his new occupation
the duties of a tavern-keeper. Van der Linde found this
fact clearly stated in the treasury accounts of the town of
Haarlem.
1451 Lou coster216 paid, for two menghelen of wine which
were sent to the bur­go­mas­ter a year ago.
1454 A dinner was offered to the count of Ooster­vant on
the 8th day of October, 1453, at lou coster’s;
indebted to him for it XVII guilders.
1468 Louris Coster and other citizens are sum­moned to
the Hague.
1474 Louris Janszoon Coster pays war taxes.
1475 Louris Janszoon Coster pays a fine for “buyten
drincken” (to drink beyond the premises).
1483 Received of Louris Janszoon Coster for ferry toll for
his goods when he left the town, 8 rex guilders.
We here see that the name of Louris Janszoon Coster
was recorded in the town-book for the last time under
the date of 1483, when he paid ferry toll for his goods,
and was allowed to leave the town. It is not known where
he went or where he died, but it is plain that the story of
his death in 1439, as related by Meerman and Koning,
must be untrue.
There might have been a doubt as to the identity of the
chandler with the innkeeper, if Van der Linde had not
investigated in another direction, and made gleanings
from the books of an old association, whose records are
as trustworthy as those of the archives of the town and
the church. This association, which still exists, under the
name of the Holy Christmas Corporation , is thus
described by Van der Linde:
It is one of those fraternities which had the lofty aim of eating and
drinking. This corporation is already very old, for it celebrated its
third jubilee in 1606. Its fifty-four brethren and sisters preserved
each a chair for their meetings. According to these statutes, these
chairs, if they were not disposed of by a last will, were inherited by
p367 the eldest and nearest blood relation in the branch from which
they came . . . . The corporation remaining in existence, the right of
property in the chairs continued, by uninterrupted transmission, until
our time.

In the register of the names of the occupants of the


chairs are found the following entries under the heading
of chair 29:
1421 Jan Coster, by . . . .
1436 Lourijs Coster, by inheritance.
1484 Frans Thomas Thomasz, by . . . .217
1497 Gerret Thomas Pieterz, by inheritance from his
father.
1564 Cornelis Gerritz, by inheritance from his father.
1589 Anna Gerritsdr., by purchase from her cousin.
The names of the successive owners of chair 29 are
continued in the book, but they are of no interest in this
inquiry.
The archives of the church and town of Haarlem
contain the names of other Costers, but there is no other
Coster who will answer the description of Junius and
Thomaszoon. The Lourens Janszoon Coster of the
pedigree, the Louwerijs Janssoen (so called only after the
year 1441) or Lourijs Coster of the archives, and the
Lourijs Coster of the chair-book are, without doubt, the
different names of the same man. This is the man who,
according to Thomaszoon and Junius, brought the first
print in the world. But he appears as a printer only in the
pedigree. The archives and the chair-book do not so
describe him; they tell us nothing of his invention, nor of
the alleged stealing of his types, nor of his death in 1439.
The town-book says that he was living in 1483. In none
of these documents does he appear as sheriff, sexton, or
treasurer.
It is obvious that the legend of Coster the printer rests
entirely upon the pedigree and its amplifications by
Junius. p368 But the pedigree is of no authority. Its
information is not confirmed by the records; its
falsifications and its suspected history compel every
candid reader to reject its evidence altogether. We have
to accept in preference the testimony of the archives, and
have to admit that there is no credible evidence that
Coster printed anything at any time. The Lourens
Janszoon Coster of typographical history is as fictitious a
personage as the Cadmus of Greek mythology. He is
really more fictitious, for he is the representative of two
men.
The revelations of Dr. Van der Linde show that Lourens
Janszoon Coster has been confounded with Laurens
Janszoon or Louwerijs Janszoon,218 who was a man of
some distinction, a wine merchant, innkeeper, councilor,
sheriff, treasurer and governor of the hospital. He is the
man of civic offices, of wealth and high social position,
who has been described by Koning. He is the man whom
Meerman represented as an p369 unrecognized member
of the noble family of Brederodes. But he is, certainly, not
the man described on the pedigree as the Coster who
brought the first print in the world. He is not the man
described by Junius who lived “about one hundred and
twenty-eight years ago,” or in 1440, for the records of the
church of St. Bavo prove that Laurens Janszoon died and
was buried in 1439. It is not at all probable that
Thomaszoon or Junius made any mistake in the name,
and that it was this Louwerijs Janszoon who brought the
first print in the world. There is no more evidence in favor
of Janszoon as an inventor of printing than there is in
favor of Coster. The most careful searching of the records
fails to bring to light any evidence that he was engaged
in the practice of printing.
That Lourens Coster kept a tavern may also be inferred
from the fact that the house he lived in was always
known as a tavern. The engraving of this house on the
following page shows how the edifice appeared in 1740.
Junius said that it was a house of some pretension in
1568, and that it stood on the market-place near the
royal palace; but Van Zuren had previously noticed it as a
house falling to decay. In 1628, Scriverius said that the
house had been “changed and was divided among three
masters:” the part supposed to be the Coster residence
was called The Golden Bunch of Grapes , and it was even
then used as a tavern. When John Bagford first saw the
house, in 1706, it was a cheese shop. In 1761, Moses
Van Hulkenroy, a printer, lived in part of it, and the other
part was occupied as an inn, then known as The Golden
Fleece . In 1813, the centre building was used as a public
house. It fell into ruins on the 13th of May, 1818, but it
has since been rebuilt, and a tablet inserted in memory of
Coster. It is probable that this house was an inn when
Junius wrote Batavia , and that he refrained from
mentioning this circumstance lest it might degrade Coster.
But we now know that Coster, and Pieter Thomaszoon,
his son-in-law, who succeeded him in business, and that
Gerrit Thomaszoon, the author of the pedigree, were all
innkeepers. The wine-flagons, to which p371 Junius points
so triumphantly, were a proper portion of the furnishings
of an inn. To the modern reader, who has been informed
that a part of this house has always been a drinking
tavern for the refreshment of the men of Haarlem, these
pewter mugs, or flagons, as Junius names them, are not,
as he would have us believe, indisputable evidence that
their first owner must have been a printer.
The House of Coster. ♠
[From Seiz.]

The falsity of the legend is abun­dantly es­tab­lished by


the dis­simi­lar­ity of the many engraved like­nesses, which
from time to time have been pre­sented as por­traits of
Coster. The earliest repre­sen­ta­tion of the alleged inventor

You might also like