6916388 Problems and Solutions in Java

212
Exercise Solutions Introduction to Programming in Java First Edition Roy Parteno Tom West Holt Software Associates Inc. Toronto, Canada

Transcript of 6916388 Problems and Solutions in Java

Page 1: 6916388 Problems and Solutions in Java

Exercise Solutions

Introduction toProgrammingin Java

First Edition

Roy Parteno

Tom West

Holt Software Associates Inc.

Toronto, Canada

Page 2: 6916388 Problems and Solutions in Java
Page 3: 6916388 Problems and Solutions in Java

Page 1

Chapter 1.11 Solutions

Exercise #1:

Describe the contribution to the development of modern computers made by thefollowing people.

(a) Charles BabbageDuring the nineteenth century, a British man, Charles Babbage, made significantadvancements in computation. He developed the concepts for two steam poweredmachines, which he called the Difference Engine and the Analytic Engine. TheDifference Engine could perform mathematical computations to eight decimalplaces. The Analytic Engine was a true ancestor of the modern computer. It was amachine capable of performing any mathematical operations from instructions on aseries of punch cards. It had a memory unit, a sequential control, and many otherfeatures of a modern computer.

(b) Pehr George ScheutzIn 1854 Swedish printer, Pehr George Scheutz, completed the work of CharlesBabbage and built a Difference Engine for calculating mathematical tables. Scheutz'smachine consisted of a memory and a central processor. He called memory the"store" and the central processor the "mill." Like the Analytic Engine, it operated bya series of punched cards that contained a series of operations and data.

(c) Herman HollerithIn 1896 Herman Hollerith formed what is considered to be the first computercompany. Hollerith was a mechanical engineer who helped tabulate the census of thepopulation of the United States In 1890 he invented a new punched card technologywhich proved much faster than traditional methods of tabulating the results andallowed the United States Census Bureau to gather more information by asking morequestions. From there, Hollerith set up his own company, the Tabulating MachinesCompany, which later became International Business Machines, known today asIBM.

(d) Allan M. TuringIn 1937 a British mathematician named Allan M. Turing developed an abstractmachine called the Turing machine. During World War II, Turing was involved intop secret work for the British military and was responsible for breaking the Germancode.

(e) Howard T. AikenHoward T. Aiken was an electromechanical engineer who collaborated with anumber of IBM engineers to design and build the Mark 1 computer. This machinecould handle negative and positive numbers, carry out long calculations in theirnatural sequence, use a variety of mathematical functions, and was fully automatic.Instructions for the Mark 1 were written on a paper tape.

Page 4: 6916388 Problems and Solutions in Java

Page 2

(f) John W. Mauchly and J. Presper Eckert Jr.In 1945 John W. Mauchly and J. Presper Eckert Jr. designed and built the first large-scale electronic digital computer from 18000 vacuum tubes and 1500 relays. Thismachine was called the ENIAC and operated at one thousand times faster than theearlier electromechanical machines.

(g) John von NeumannJohn von Neumann played a role in both the ENIAC and EDVAC projects. TheEDVAC improved on the ENIAC in many ways. EDVAC was capable of storing aprogram in memory and breaking computations down into a series or sequence ofsteps that could be performed one at a time. It also used binary notation to store andmanipulate numbers.

(h) Charlotte FroseIn 1952 the University of Toronto purchased a computer from Ferranti Electric andcalled it FERUT. Charlotte Frose was one of the many women programmers whoworked on the FERUT project.

(i) Ada ByronAda Byron is believed to be the first computer programmer. Byron correspondedwith many English mathematicians including Charles Babbage. While Babbageconcentrated on designing the computer hardware, Ada Byron became the firstperson to develop a set of instructions, which came to be called computer programs.

(j) Grace HopperGrace Murray Hopper helped to invent the COBOL programming language. COBOLwas designed to help process business data and was heavily used by many industriesincluding banking and insurance.

Page 5: 6916388 Problems and Solutions in Java

Page 3

Exercise #2:

List the five generations of computers along with two significant features of eachgeneration.

Generation 1 occurred between 1951-1958-vacuum tubes-card input/output

Generation 2 occurred between 1959-1964-integrated circuits-magnetic tape I/O

Generation 3 occurred between 1965-1970-minicomputers-disk I/O

Generation 4 occurred between 1970-1980-LSI-VLSI

Generation 5 occurred 1980 +-RISC-parallel computers

Exercise #3:

Define the following:

(a) computer programmingThe task of inputting instructions into the computer.

(b) programming languageA set of symbols, characters, and rules, much like a spoken language.

(c) syntaxThe rules of grammar in a programming language.

(d) debugFinding and correcting errors in a computer program.

Page 6: 6916388 Problems and Solutions in Java

Page 4

Exercise #4:

Explain two differences between machine and assembly language.Machine language refers to the binary representation of code and outputs code inbinary form. Assembly language allows the programmer to simplify writteninstructions using letter symbols rather than operation code. The assembler thentranslates the written instructions into machine language.

Exercise #5:

List three advantages of assembly languages over machine languages.Assembly language has three advantages over machine languages. They are:

• easier and faster to write,

• easier to debug, and

• easier to change at a later date.

Exercise #6:

Differentiate between a compiler and an interpreter.While a compiler translates the source program and permanently saves the objectcode for later use, the interpreter converts each source program statement intomachine language every time the program is run.

Page 7: 6916388 Problems and Solutions in Java

Page 5

Exercise #7:

List five high-level programming languages.• ADA

• BASIC

• COBOL

• C

• FORTRAN

• LISP

• Logo

• Pascal

• Turing

Exercise #8:

State one feature of each of the five high-level languages identified in the exercise aboveand list the most important person(s) involved with each language.

ADA - designed for military use by the United States Department of defense.

BASIC - designed as an easy-to-learn language for general computing by JohnKemeny and Thomas Kurtz.

COBOL - designed to process business data by Grace Murray Hopper.

C - designed to program large systems by Brian Kernighan.

FORTRAN -designed for expressing mathematical equations by John Backus.

LISP - designed to support research in artificial intelligence by John McCarthy.

Logo - developed to help young children explore a mathematical environment bySeymour Papert.

Pascal - designed to support the concepts of structured programming by NiklausWirth.

Turing - designed to a specified syntax that was much easier to understand by RicHolt and James Cordy.

Page 8: 6916388 Problems and Solutions in Java

Page 6

Exercise #9:

Machine and assembly languages are both examples of ñlow-level languagesî. List fiveadvantages high-level languages have over low-level languages.

• Can be run on different makes of computers with minimal modification.

• Easier for programmers to learn.

• Easier to maintain.

• Faster and easier to write than assembly languages.

• Free programmers from concerns about low-level machine details.

Exercise #10:

Define programming paradigm.A programming paradigm is a set of ideas which forms the basis of a particular wayof programming, for example structured programming and object-orientedprogramming.

Exercise #11:

Explain the main differences between two programming paradigms.Structured programming involves the design of programs using modular concepts ina top-down fashion. Object-oriented programming is a method of designing andwriting programs based on the concept that a program is a collection of objectswhich work together.

Page 9: 6916388 Problems and Solutions in Java

Page 7

Exercise #12:

Draw a simple model of a computer.

Exercise #13:

What does the acronym CPU stand for?The acronym stands for Central Processing Unit.

Exercise #14:

State the main function of the CPU.The CPU does the work and determines the order in which operations areperformed.

Exercise #15:

State the three main sections of the CPU.The three main sections of the CPU are:

• the primary storage section,

• the arithmetic-logic section, and

• the control section.

Page 10: 6916388 Problems and Solutions in Java

Page 8

Exercise #16:

Explain the functions of each of the three sections of the CPU.The primary storage section has four tasks. The input storage area collects data thathas been fed in until it is ready to be processed. The program storage area holds theprocessing instructions. The working storage space holds the data being processedand the intermediate results of that processing. Finally, the output storage area holdsthe final results of the processing operations until they can be released.

The arithmetic-logic section is where the data held in the storage areas is processed.Once processing is complete, final results are sent to the output storage section andfrom there to an output device (such as a monitor, or printer).

The control section directs data to the appropriate places in the CPU. Programinstructions are selected and carried out sequentially until the processing iscompleted.

Exercise #17:

Explain the significance of each of the following terms relating to computer memory.

(a) main memoryMain memory is the primary storage section of the Central Processing Unit.

(b) RAMRandom Access Memory stores programs, data, or information from input andoutput devices. This memory is lost when the computer is shut off.

(c) ROMRead-Only Memory stores information that the system needs to function. Thismemory is stored at the time the computer was manufactured and is not lost whenthe computer is shut off.

(d) vacuum tubesVacuum tubes were early electrical devices made of glass and used to control the flowof electricity in a circuit.

(e) magnetic coreThe magnetic core consists of small ring-shaped pieces of metal that can bemagnetized in one of two directions.

(f) siliconSilicon is a popular semiconducting material used to make computer chips.

(g) back-upA back-up is an additional copy of documents, files, or applications.

Page 11: 6916388 Problems and Solutions in Java

Page 9

Exercise #18:

The binary number system is fundamental to really understanding how a computerfunctions. Explain.

While human beings use the Base 10 number system to count, computers use theBase 2, or binary, number system. Because humans and computers use these twodifferent number systems, humans who need to communicate with computers attheir most fundamental level need to be able to convert between and understand thebinary and decimal number systems.

Exercise #19:

Explain the difference between hardware and software.Hardware refers to the electronic and mechanical parts of the computer, externaldevices, and peripherals. These include the hard disk, keyboard, mouse and so on.Software is a set of computer programs, procedures, and documentation concernedwith the operation of a computer system.

Exercise #20:

List one significant feature (besides size) of each type of computer.

(a) supercomputerSupercomputers have multiple CPUs and are known for their processing speed.

(b) mainframeA mainframe is capable of multiprocessing and has the ability to store vast amountsof information and later to distribute it.

(c) minicomputerMinicomputers are used along with mainframe computers. These usually have morepower and a wider range of available software than smaller computers.

(d) personal computerPersonal computers are designed for a single user and are comprised of a CPU,input/output units, and a power supply.

(e) laptopLaptop computers are designed to provide most of the same features of a personalcomputer, but in a more portable size. These are often characterized by a smallerkeyboard and a flip-top lid containing a monitor or screen.

(f) palmtopPalmtop computers are often used as personal organizers, word processors, or foraccessing local or global telecommunications such as electronic mail.

Page 12: 6916388 Problems and Solutions in Java

Page 10

Exercise #21:

What is a silicon chip?A silicon chip is a computer chip which contains silicon. Silicon has uniqueproperties which make it especially useful in the manufacturing of electronicsequipment.

Exercise #22:

List three features of silicon chips.• A silicon chips can be used as a conductor, insulator, or switch.

• Silicon chips are made up of large numbers of transistors which are organizedinto circuits.

• Silicon chips are often called integrated circuits because each chip can containmany different circuits.

Exercise #23:

List three types of software and one feature of each type.• Application software - a program or set of programs designed to meet a specificuser need such as word processors and spreadsheets.

• Operating systems - a collection of programs that the computer uses to manageitself and use its resources efficiently.

• Programs - a sequence of instructions for a computer, written in a programminglanguage, which translates the instructions to a form the computer can understand.

• Programming environments - a set of tools that includes an editor for enteringand changing the program, a compiler or interpreter for translating programs into amachine language that the computer can understand, and sometimes a debugger forlocating and fixing errors.

Exercise #24:

Computers can be used to obtain personal information without your knowledge. Explain.As computers become more common in every aspect of our lives, the amount ofinformation that can be collected about people is growing. Governments collectinformation about people’s income, insurance companies collect information aboutpeople’s health, and credit card companies collect information about how peoplespend their money. Information about every aspect of a person's life can be collectedand sold to businesses and organizations without the person agreeing or evenknowing. For example, optical scanners in grocery stores can be used to collectinformation about what kinds of products people buy and that information can thenbe sold to other companies who make or advertise those products.

Page 13: 6916388 Problems and Solutions in Java

Page 11

Exercise #25:

Computers have created many new job opportunities. Explain.Since there is almost no industry now that does not require the skills ofprogrammers, computers have created many new job opportunities. These jobs helpbusinesses streamline their operation and provide services more efficiently. Theseimprovements include easier access to goods and services such as Internet shopping,more reliable billing procedures, and faster and more detailed access to customerinformation.

Exercise #26:

Computers have eliminated many jobs. Explain.Computerization of many traditional manufacturing industries has led to thedisplacement of many workers. The growing use of computers has also eliminatedmany of the jobs formerly performed by skilled tradespeople or even by unskilledworkers.

Page 14: 6916388 Problems and Solutions in Java

Page 12

Chapter 3.9 Solutions

Exercise #1:

Define programming paradigm.A programming paradigm is a set of ideas which forms the basis of a particular wayof programming, for example structured programming and object-orientedprogramming.

Exercise #2:

Explain the main differences between two programming paradigms.Structured programming involves the design of programs using modular concepts ina top-down fashion. Object-oriented programming is a method of designing andwriting programs based on the concept that a program is a collection of objectswhich work together.

Exercise #3:

Define the following:

(a) algorithmAn algorithms is a sequence of steps used when solving a programming problem.

(b)hackerHacker is a negative term used to denote a person who uses computers to play pranksor to undertake illegal activities.

(c) virusA virus is a program, which when inadvertently downloaded, interferes with theoperations of or damages a computer or network.

Page 15: 6916388 Problems and Solutions in Java

Page 13

Chapter 4.9 Solutions

Exercise #1:

Write the method square with the signature

void square (int x, int y, int size, Color clr)

which when called, draws a square of size pixels in color clr. The upper-left corner of thesquare will be at (x, y). Use the method in an application program to place a yellow squareof size about one quarter of the window width with its center in the center of the window.

Solution

// Chapter #4 - Exercise #1 (C0401)

import java.awt.*;import hsa.Console;

public class C0401{

static Console c;

static public void main (String args []){

int xc, yc, sizec;c = new Console ();// Calculate the display values.xc = c.maxx () / 8 * 3;yc = c.maxy () / 8 * 3;sizec = c.maxx () / 4;// Call square.square (xc, yc, sizec, Color.yellow);

} // main method

static public void square (int x, int y, int size, Color clr){

c.setColor (clr);c.drawRect (x, y, size, size);

} // square method} // C0401 class

Page 16: 6916388 Problems and Solutions in Java

Page 14

Exercise #2:

Write the method block with the signature

void block (int x, int y, int size, Color clr)

which produces a filled square. Use this in an application program to draw a series ofblocks of four different colors across the bottom of the window.

Solution

// Chapter #4 - Exercise #2 (C0402)

import java.awt.*;import hsa.Console;

public class C0402{

static Console c;

static public void main (String args []){

int yc, sizec;c = new Console ();// Calculate the display values.sizec = c.maxx () / 4;yc = c.maxy () – sizec;// Call block four times.block (0, yc, sizec, Color.yellow);block (c.maxx () / 4, yc, sizec, Color.red);block (c.maxx () / 2, yc, sizec, Color.blue);block (c.maxx () / 4 * 3, yc, sizec, Color.green);

} // main method

static public void block (int x, int y, int size, Color clr){

c.setColor (clr);c.fillRect (x, y, size, size);

} // block method} // C0402 class

Page 17: 6916388 Problems and Solutions in Java

Page 15

Exercise #3:

Use a repetition construct in a program to draw a pattern of three black blocks separatedby three red squares of the same size across the top of the window. Make the squares orblocks as large as will fit into the width of the window. This size will be getWidth()/6.Hint: Use this construct to draw the three black blocks:

int size = c.getWidth () / 6; for (int xcorn = 0; xcorn <= 4 * size; xcorn = xcorn + 2 * size)

{block (xcorner, 0, size, clr);

}

Solution

// Chapter #4 - Exercise #3 (C0403)

import java.awt.*;import hsa.Console;

public class C0403{

static Console c;

static public void main (String args []){

c = new Console ();// Declare and initialize the display values.int yc = 0;int size = c.maxx () / 6;// Draw the blocks. See the textbook for a hint.for (int xcorn = 0 ; xcorn <= 4 * size ; xcorn = xcorn + 2 * size){

block (xcorn, 0, size, Color.black);}// Draw the squares using the same type of loop as for the blocks.for (int xcorn = size ; xcorn <= 6 * size ; xcorn = xcorn + 2 * size){

square (xcorn, 0, size, Color.red);}

} // main method

static public void square (int x, int y, int size, Color clr){

c.setColor (clr);c.drawRect (x, y, size, size);

} // square method

static public void block (int x, int y, int size, Color clr){

c.setColor (clr);c.fillRect (x, y, size, size);

} // block method} // C0403 class

Page 18: 6916388 Problems and Solutions in Java

Page 16

Exercise #4:

Write a program that uses the moon method of this chapter to draw three blue moonsspaced apart and centered on the window. Choose an appropriate size for the radius ofthe moon.

Solution

// Chapter #4 - Exercise #4 (C0404)

import java.awt.*;import hsa.Console;

public class C0404{

static Console c;

static public void main (String args []){

c = new Console ();// Declare and initialize the display values.int yc = c.maxy () / 2;int size = c.maxx () / 4;int moonSize = size / 4;// Draw the moons.for (int xc = size ; xc <= 3 * size ; xc = xc + size){

moon (xc, yc, moonSize, Color.blue);}

} // main method

… moon method …

… tiltSquare method …} // C0404 class

Page 19: 6916388 Problems and Solutions in Java

Page 17

Exercise #5:

Create a circle of red balls arranged like beads on a string. To solve this problem, begin bycreating a method that draws a ball of radius, positioned so that its center (xc, yc) is at theend of a stick of length size whose other end is at the point (xp, yp), and which makes anangle angle with the x-axis (the horizontal). Figure 4.7 shows this.

Figure 4.7 Ball on a Stick

The method would have the following signature.

void ballOnStick (int xp, int yp, int size, int radius, Color clr)

Note that the point in the tiltSquare method of this chapter (x2, y2) corresponds to thecenter of the ball.

Use the ballOnStick method to create a method that draws a circle of balls using the forrepetition construct. Decide what the step size in the angle must be in order for the ballsto just touch. What happens if it is smaller than this size?

Solution

// Chapter #4 - Exercise #5 (C0405)// The step size of 30 is used to make the circles just touch,// if the step is slightly smaller than 30, for example 28 or 29,// some of the circles will overlap.

import java.awt.*;import hsa.Console;

public class C0405{

static Console c;

static public void main (String args []){

Page 20: 6916388 Problems and Solutions in Java

Page 18

c = new Console ();// Call the method to draw the beads.drawBeads ();

} // main method

static public void drawBeads (){

// Declare and initialize the display values.Color clr = Color.red;int yc = c.maxy () / 2;int xc = c.maxx () / 2;

int size = c.maxx () / 10;int radius = 16;// Draw the red circles on a string.for (int angle = 0 ; angle <= 340 ; angle = angle + 30){

ballOnStick (xc, yc, size, radius, angle, clr);}

} // drawBeads method

static public void ballOnStick (int x1, int y1, int size, int radius,int angle, Color clr)

{// Change angle to radians.double rAngle = angle * Math.PI / 180;// Compute two constants to help compute centre of a red circle.final int A = (int) Math.round (size * Math.cos (rAngle));final int B = (int) Math.round (size * Math.sin (rAngle));// Compute the corners.int x2 = x1 + A;int y2 = y1 – B;circle (x2, y2, radius, Color.red);

} // ballOnStick method

static public void circle (int xc, int yc, int radius, Color clr){

int width = radius * 2;int height = radius * 2;int x = xc – radius;int y = yc – radius;c.setColor (clr);c.drawOval (x, y, width, height);

} // circle method} // C0405 class

Page 21: 6916388 Problems and Solutions in Java

Page 19

Chapter 5.10 Solutions

Exercise #1:

Which of these identifiers is syntactically correct?

a) sum

b) 3rdPage

c) two+two

d) Fixed_Price

e) high-level

Solution

a) correct

b) incorrect - identifier cannot start with a digit

c) incorrect - cannot use the + sign

d) correct - but Java conventions suggest starting with a lower case letter

e) incorrect - the hyphen cannot be used

Exercise #2:

The arithmetic expression

3 * 5 + 7 − 2/6

has a value 21.666ƒ. What value would be computed? Write the same expression with allparentheses included.

What are the values of the following expressions?

(a) 3 * ((5 + 7) − 2)/6(b) 3 * 5 + (7 − 2)/6(c) ((3 * 5) + 7 − 2)/6

Solution

The expression would be written as (3*5)+7-(2/6).

a) = 5

b) = 15.833...

c) = 3.333...

Page 22: 6916388 Problems and Solutions in Java

Page 20

Exercise #3:

Write a program that computes the interest on a bank balance to the nearest cent andstores the result in a variable called newBalance. Prove that the new balance is stored tothe nearest cent by an output instruction that prints newBalance with three decimalplaces. Test the program using a variety of values assigned to the balance and the interestrate.

Solution

// Chapter #5 - Exercise #3 (C0503)

import java.awt.*;import hsa.Console;

public class C0503{

static Console c;

static public void main (String args []){

c = new Console ();// Declare the variables.double currentBalance, rate, interest, newBalance;// Assign the initial values of current bank balance// and interest rate.currentBalance = 526.45;rate = .04;// Calculate the new balance.interest = Math.round (currentBalance * rate * 100) / 100;newBalance = currentBalance + interest;// Display the new balance.c.print ("The new balance is ");c.println (newBalance, 6, 3);

} // main method} // C0503 class

Page 23: 6916388 Problems and Solutions in Java

Page 21

Exercise #4:

What is output by the following statements involving boolean expressions?

c.println ( 5 > 3 && 7 > 9 || 6 < 8);c.println ( 2 < 6 && 5 < 10 && 7 > 3);

Solution

c.println (5>3 && 7>9 || 6<8)

5>3 is true, 7>9 is false, 6<8 is true

5>3 && 7>9 || 6<8 becomes true AND false OR true

which is (true AND false) OR true

which is false OR true

which is true

c.println (2<6 && 5<10 && 7>3)

2<6 is true, 5<10 is true, 7>3 is true

2<6 && 5<10 && 7>3 becomes true AND true AND true

which is (true AND true) AND true

which is true AND true

which is true

Page 24: 6916388 Problems and Solutions in Java

Page 22

Exercise #5:

What is output by this program segment?

int sum = 0;for (int count = 1; count <= 10; count ++){

c.println ("sum = " + sum + " count = " + count);sum += 1;

}c.println ("sum = " + sum);

What would be the output if the incrementation part of the for were count += 2? See whathappens if an attempt is made to output count in the last println statement.

Solution

The output is:

sum = 0 count = 1

sum = 1 count = 2

sum = 2 count = 3

sum = 3 count = 4

sum = 4 count = 5

sum = 5 count = 6

sum = 6 count = 7

sum = 7 count = 8

sum = 8 count = 9

sum = 9 count = 10

sum = 10

If the incrementation was count +=2 the output would be:

sum = 0 count = 1

sum = 1 count = 3

sum = 2 count = 5

sum = 3 count = 7

sum = 4 count = 9

sum = 5

If count was used after the last println statement, an error would occur as count isdeclared within the for structure as a temporary variable and cannot be used outsidethe loop.

Page 25: 6916388 Problems and Solutions in Java

Page 23

Chapter 6.12 Solutions

Exercise #1:

Write a program that creates a table of the even integers and their squares. The columnsof the table should be properly labelled. Arrange that the values of integers go from 10 to360. Store this table in a file called squares. Now, in the same program, read the fileñsquaresî and add a third column which is the square root of the squares column. Storethe output in the file table2. Using the environment editor, examine the file table2 to seehow closely the first and third columns agree.

Solution

// Chapter #6 - Exercise #1 (C0601)// This exercise uses features that are not introduced till later chapters.// This question should be held off until those features have been introduced.

import java.awt.*;import java.io.*; // Needed for file I/O.import java.util.*; // Needed for StringTokenizer class.import hsa.Console;

public class C0601{

static Console c;

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

c = new Console ();int square, squareValue;String temp, oneLine;double root;// Open the file for output.PrintWriter output = new PrintWriter (new FileWriter ("squares"));// Generate the squares of numbers from 10 to 360.for (int ctr = 10 ; ctr <= 360 ; ctr += 2){

square = ctr * ctr;output.println (Integer.toString (ctr) + " " + square);

}output.close ();c.println ("The file 'squares' has been created");// Open the file, read the square values, calculate square root// and save the updated values to a file called table2.BufferedReader input = new BufferedReader (new FileReader

("squares"));PrintWriter outputTable = new PrintWriter (new FileWriter

("table2"));// Loop to process all lines in squares.oneLine = input.readLine ();while (oneLine != null )

Page 26: 6916388 Problems and Solutions in Java

Page 24

{StringTokenizer line = new StringTokenizer (oneLine);temp = line.nextToken ();squareValue = Integer.parseInt (line.nextToken ());root = Math.sqrt (squareValue);outputTable.println (temp + " " + squareValue + " " + root);oneLine = input.readLine ();

}outputTable.close ();c.println ("The file 'table2' has been created");

} // main method} // C0601 class

Page 27: 6916388 Problems and Solutions in Java

Page 25

Exercise #2:

Write a program that generates a student’s exam mark out of 100 by producing 10random numbers ranging from 0 to 10 and adding them. Output the sequence of 10marks and their average.

Solution

// Chapter #6 - Exercise #2 (C0602)

import java.awt.*;import hsa.Console;

public class C0602{

static Console c;

static public void main (String args []){

c = new Console ();double average;int oneMark, sumMarks = 0;// Loops from 1 to 10 to generate 10 marks.for (int ctr = 1 ; ctr <= 10 ; ctr++){

// Random * 11 produces numbers ranging from 0 to 10.999...// (int) rounds the result down to a value from 0 to 10.oneMark = (int) (Math.random () * 11);sumMarks += oneMark;c.println ("The mark is " + oneMark); // Display each mark.

}average = sumMarks / 10.0;c.println ("The sum is " + sumMarks); // Display the sum.// Display the average in decimal format.c.println ("The average is " + average);

} // main method} // C0602 class

Page 28: 6916388 Problems and Solutions in Java

Page 26

Exercise #3:

A series of marks for an examination is to be averaged. Write a program that first asks theuser to enter the number of marks in the series then generates this number of marks bythe method shown in Exercise 2. Test it for the extreme cases where the number is 0 or 1.

Solution

// Chapter #6 - Exercise #3 (C0603)

import java.awt.*;import hsa.Console;

public class C0603{

static Console c;

static public void main (String args []){

c = new Console ();int oneMark, numMarks, sumMarks;// Get number of marks.c.print ("How many marks would you like to generate? ");numMarks = c.readInt ();// Loop for number of marks.for (int outer = 1 ; outer <= numMarks ; outer++){

// Set sum to 0 each time through outer loop.sumMarks = 0;// Loops from 1 to 10 to generate 10 marks.for (int inner = 1 ; inner <= 10 ; inner++){

// random * 11 produces numbers ranging from 0 to 10.999...// (int) rounds the result down to a value from 0 to 10.oneMark = (int) (Math.random () * 11);sumMarks += oneMark;

}// Display each mark.c.println ("Mark # " + outer + " is " + sumMarks);

}c.println ();c.println ("The program has ended");

} // main method} // C0603 class

Page 29: 6916388 Problems and Solutions in Java

Page 27

Exercise #4:

Prepare a file called exammark of 100 generated exam marks using the method of exercise2, that is, where each mark is a sum of 10 random integers between 0 and 10. Find theaverage and variance of the marks stored in the file exammark.

Solution

// Chapter #6 - Exercise #4 (C0604)

import java.awt.*;import java.io.*;import hsa.Console;

public class C0604{

static Console c;

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

c = new Console ();int oneMark, sumMarks, sumSquares;double variance, average;int mark;String line;PrintWriter output = new PrintWriter (new FileWriter

("exammark.txt"));// First create the file exammark.// Loop for number of marks.for (int outer = 1 ; outer <= 100 ; outer++){

// Set sum to 0 each time through the outer loop.sumMarks = 0;// Loops from 1 to 10 to generate 10 marks.for (int inner = 1 ; inner <= 10 ; inner++){

// Random*11 produces numbers ranging from 0 to 10.999...// (int) rounds the result down to a value from 0 to 10.oneMark = (int) (Math.random () * 11);sumMarks += oneMark;

}output.println (sumMarks); // Write each mark to the file.

}c.println ();c.println ("The file exammark.txt has been created");output.close ();sumMarks = 0;sumSquares = 0;BufferedReader input;input = new BufferedReader (new FileReader ("exammark.txt"));for (int ctr = 1 ; ctr <= 100 ; ctr++){

Page 30: 6916388 Problems and Solutions in Java

Page 28

line = input.readLine ();mark = Integer.parseInt (line);sumMarks += mark;sumSquares += (mark * mark);

}average = sumMarks / 100.0;variance = sumSquares / 100.0 – (average * average);c.println ("The average is " + average);c.println ("The variance is " + variance);

} // main method} // C0604 class

Page 31: 6916388 Problems and Solutions in Java

Page 29

Chapter 7.11 Solutions

Exercise #1:

A sequence of integers is stored in a file called ages. Write a program to find the range ofages present, that is the difference between the oldest and the youngest.

Solution

// Chapter #7 - Exercise #1 (C0701)

import java.awt.*;import java.io.*; // Needed for file access.import hsa.Console;

public class C0701{

static Console c;

// Throws IOException must be added when accessing files.static public void main (String args []) throws IOException{

c = new Console ();String line, fileIn;int age, high = 0, low = 0, range;BufferedReader input;// The loop continues until the user enters a valid file name.while (true){

try // Attempt to access the file named by the user.{

c.print ("Enter the file name: ");fileIn = c.readLine ();// Open file as an object named input.input = new BufferedReader (new FileReader (fileIn));break ;

}// If there is an exception, an error message displays.catch (IOException e){

c.println ("File does not exist");}

}// Read one line before the loop.line = input.readLine (); // Read a line of characters.if (line != null ) // Make the first value both high and low.{

high = Integer.parseInt (line);low = Integer.parseInt (line);// Read until there is no more data in the file.while (line != null ) // File is terminated by a null.

Page 32: 6916388 Problems and Solutions in Java

Page 30

{age = Integer.parseInt (line); // Change to an integer.if (age > high) // Determine if there is a new low or high.

high = age;if (age < low)

low = age;line = input.readLine (); // Read next line.

}}range = high – low;c.println ("The range of ages between the ages of " + low + " and " +

high + " is " + range + " years");} // main method

} // C0701 class

Page 33: 6916388 Problems and Solutions in Java

Page 31

Exercise #2:

Write a program to show how a mortgage on a house will be paid off (amortized) over acertain number of years given the amount of the mortgage, the proposed annual payment,and the annual interest rate charged.

Prepare a table showing the amount of interest and capital paid in each year, and the finalbalance owing at the year’s end. Label the columns of the table. Show also the totalinterest paid during the amortization.

Solution

// Chapter #7 - Exercise #2 (C0702)// In the preparation of the amortization chart// a minimum payment is calculated.

import java.awt.*;import hsa.Console;

public class C0702{

static Console c;

static public void main (String args []){

c = new Console ();int yearCtr = 0;double principal, interest, rate , payment, minPayment;double capitalPaid = 0;double totalInterest = 0;// Get initial values.c.println ("Enter the mortgage amount");principal = c.readDouble ();c.println ("Enter the rate of interest in decimal form");rate = c.readDouble ();// Calculate and request minimum payment amount.// Good extension activity to error trap here.minPayment = principal * rate + 10;c.print ("Enter a payment greater than ");c.println (minPayment, 8, 2);payment = c.readDouble ();// Report heading.c.println ();c.println ("Year Capital Interest Balance");c.println ("======================================");// Continue until the loan is paid.while (principal > 0) // File is terminated by a null.{

// Calculate new amounts.interest = principal * rate;totalInterest += interest;// Looks after last payment.

Page 34: 6916388 Problems and Solutions in Java

Page 32

if (payment > (principal + interest)){

payment = principal + interest;capitalPaid = principal;

}capitalPaid = (payment – interest);principal –= capitalPaid;yearCtr++;// Print extra space when year is single digit.if (yearCtr < 10)

c.print (" " + yearCtr);else

c.print (" " + yearCtr);c.print (capitalPaid, 10, 2);c.print (" ");c.print (interest, 10, 2);c.print (" ");c.print (principal, 10, 2);c.println (" ");

}// print summary linesc.println ("======================================");c.print (" Interest->");c.println (totalInterest, 10, 2);

} // main method} // C0702 class

Page 35: 6916388 Problems and Solutions in Java

Page 33

Exercise #3

Federal income tax is charged at these rates:

17% on the first $29,590 of taxable income,

26% on the next $29,590 of taxable income, and

29% on any income in excess of $59,180.

Write a program to compute the tax for any taxable income submitted by the user. Havethe program work for a series of taxpayers until a negative taxable income is entered.

Solution

// Chapter #7 - Exercise #3 (C0703)import java.awt.*;import hsa.Console;public class C0703{

static Console c;static public void main (String args []){

c = new Console ();double taxableIncome, tax;c.print ("Enter your taxable income: ");taxableIncome = c.readDouble ();// Program terminated by negative income.while (taxableIncome > 0){

// Determine the correct tax amount.tax = 0;if (taxableIncome <= 29590)

tax = .17 * taxableIncome;else if (taxableIncome <= 59180)

tax = (taxableIncome – 29590) * .26 + (.17 * 29590);else

tax = (taxableIncome – 59180) * .29 + (.17 * 29590)+ (.26 * 29590);

// Output the correct tax.c.print ("On taxable income of ");c.print (taxableIncome, 5, 2);c.print (" the tax is ");c.println (tax, 5, 2);c.println ();c.print ("Enter your taxable income: ");taxableIncome = c.readDouble ();

}c.println ();c.println ("Thank you for using the tax program, click " +

"Quit to exit");} // main method

} // C0703 class

Page 36: 6916388 Problems and Solutions in Java

Page 34

Exercise #4

Simulated data representing exam marks out of 100 can be prepared by generating eachmark as the sum of marks of 10 questions each out of 10. Generate a mark for eachquestion as a random integer from 0 to 10. The exam marks so generated will not beuniformly distributed, as the integers generated by a single call to random, but will beclose to a normal or Gaussian distribution (sometimes referred to as a Bell curve). Preparea file of simulated data representing a class of 200 students and call it examdata.

Solution

// Chapter #7 - Exercise #4 (C0704)

import java.awt.*;import java.io.*; // Must be included for file access.import hsa.Console;

public class C0704{

static Console c;

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

c = new Console ();int mark, markTotal ;PrintWriter output;output = new PrintWriter (new FileWriter ("examdata"));// Outside loop for 200 marks.for (int recCtr = 1 ; recCtr <= 200 ; recCtr++){

markTotal = 0;// Inside loop for 10 marks.for (int markCtr = 1 ; markCtr < 11 ; markCtr++){

// Random*11 produces numbers ranging from 0 to 10.999...// (int) rounds the result down to a value from 0 to 10.mark = (int) (Math.random () * 11);markTotal += mark;

}output.println (markTotal);

}c.println ("The file output is complete");output.close ();

} // main method} // C0704 class

Page 37: 6916388 Problems and Solutions in Java

Page 35

Exercise #5

Write a statistical analysis program. It is to read the file examdata prepared in theprevious exercise and determine the percentage of the class that would get various grades:A (80 or over), B (70-79), C (60-69), D (50-59), and F (below 50). Have it tabulate thesestatistics. Run this analysis program again using, as input, a file of simulated data ofuniformly distributed exam marks. Compare the results with those that are closer to a Bellcurve.

Solution

// Chapter #7 - Exercise #5 (C0705)// NOTE: Due to the method of mark generation, there will be few// or even no A's, and few B's.

import java.awt.*;import java.io.*;import hsa.Console;

public class C0705{

static Console c;

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

c = new Console ();int markA = 0, markB = 0, markC = 0, markD = 0, markF = 0,

mark, markCtr;double pctA, pctB, pctC, pctD, pctF;String fileName, line;markCtr = 0;// Open marks file.c.print ("Enter the name of the file of marks: ");fileName = c.readLine ();BufferedReader input;input = new BufferedReader (new FileReader (fileName));// Read the first data line.line = input.readLine (); // Read a line of characters.while (line != null ) // File is terminated by a null.{

mark = Integer.parseInt (line); // Change to an integer.// Count the number of each type of mark.if (mark >= 80)

markA++;else if (mark >= 70)

markB++;else if (mark >= 60)

markC++;else if (mark >= 50)

markD++;

Page 38: 6916388 Problems and Solutions in Java

Page 36

elsemarkF++;

line = input.readLine (); // Read next line.}markCtr = (markA + markB + markC + markD + markF);// Convert to double to avoid integer rounding to zero.pctA = (double ) markA / markCtr * 100.0;pctB = (double ) markB / markCtr * 100.0;pctC = (double) markC / markCtr * 100.0;pctD = (double ) markD / markCtr * 100.0;pctF = (double) markF / markCtr * 100.0;// Outputc.println ();c.println ();c.println ("Grade Pct");c.println ("==========");c.println ();c.print (" A ");c.println (pctA, 5, 1);c.print (" B ");c.println (pctB, 5, 1);c.print (" C ");c.println (pctC, 5, 1);c.print (" D ");c.println (pctD, 5, 1);c.print (" F ");c.println (pctF, 5, 1);

} // main method} // C0705 class

Page 39: 6916388 Problems and Solutions in Java

Page 37

Chapter 8.12 Solutions

Exercise #1

Write a program to read text from a given file and reformat it so that the lines are nolonger than a given maximum length. Instead of having it left justified with a ragged righthave it right justified with a ragged left. Store the result in a file called right, as well asdisplaying it on the screen.

Solution

// Chapter #8 - Exercise #1 (C0801.java)

import java.awt.*;import java.io.*;import java.util.*;import hsa.Console;

public class C0801{

static Console c;

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

c = new Console ();String inputLine, newLine;StringTokenizer inline;StringBuffer outline = new StringBuffer ();String infileName = "", outfileName;BufferedReader input;// Get file name and output line length from the user.int maxLength, outLength ;c.print ("Enter the maximum length of line: ");maxLength = c.readInt ();while (true){

try{

c.print ("Enter the name of the input file: ");infileName = c.readLine ();// Open the output file.input = new BufferedReader (new FileReader (infileName));break ;

}catch (IOException ioe){

c.println ("The file " + infileName + " is not found, " +"please try again");

}}

Page 40: 6916388 Problems and Solutions in Java

Page 38

// Get the name of the output file and open it.c.print ("Enter the name of the output file: ");outfileName = c.readLine ();PrintWriter output;output = new PrintWriter (new FileWriter (outfileName));// Get the first line of the text.inputLine = input.readLine ();// Loop until the input file is empty.while (inputLine != null ){

// Break a line into tokens.inline = new StringTokenizer (inputLine);while (inline.hasMoreTokens ()){

String token = inline.nextToken ();// If the word fits into the line, add it.if (outline.length () + token.length () + 1 <= maxLength){

// If there is text before it, add a space.if (outline.length () > 0){

outline.append (" ");}outline.append (token);

}// If there is no text before it, start a new line.else{

// Pad left with spaces to exact line length.while (outline.length () < maxLength){

outline.insert (0, " ");}output.println (outline);outline = new StringBuffer (token);

}} // while (inline.hasMoreTokens ())// Output the rest of the line.// Pad left with spaces to exact line length.while (outline.length () < maxLength){

outline.insert (0, " ");}output.println (outline);outline = new StringBuffer ();// Read in a new line.inputLine = input.readLine ();

} // while (inputLine != null)// Process remaining partial line and close file.newLine = outline.toString ();outLength = newLine.length ();outline = new StringBuffer ();

Page 41: 6916388 Problems and Solutions in Java

Page 39

for (int ctr = 1 ; ctr <= (maxLength – outLength) ; ctr++){

outline.append (" ");}outline.append (newLine);output.println (outline);input.close ();output.close ();c.println ("The new file has been created");

} // main method} //C0801 class

Page 42: 6916388 Problems and Solutions in Java

Page 40

Exercise #2

Write a program to read lines of text from a file called right and center each line in a spacethat is 80 characters wide. Display the result on the screen and store it in the file calledcenter.

Solution

// Chapter #8 - Exercise #2 (C0802.java)

import java.awt.*;import java.io.*;import java.util.*;import hsa.Console;

public class C0802{

static Console c;

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

c = new Console ();String inputLine, wordsLine;

StringBuffer outline = new StringBuffer ();StringBuffer tempLine;String infileName = "", outfileName;BufferedReader input;while (true){

try{

c.print ("Enter the name of the input file: ");infileName = c.readLine ();// Open the output file.input = new BufferedReader (new FileReader (infileName));break ;

}catch (IOException ioe){

c.println ("The file " + infileName + " is not found, " +"please try again");

}}// Open the input file.input = new BufferedReader (new FileReader (infileName));// Get the name of the output file and open it.c.print ("Enter the name of the output file: ");outfileName = c.readLine ();PrintWriter output;output = new PrintWriter (new FileWriter (outfileName));

Page 43: 6916388 Problems and Solutions in Java

Page 41

// Get the first line of the text.inputLine = input.readLine ();int lineLength = 0;// Loop until the input file is empty.while (inputLine != null ){

StringTokenizer inLine = new StringTokenizer (inputLine);tempLine = new StringBuffer ();// Run through the Tokenizer to get rid// of the leading spaces.while (inLine.hasMoreTokens ()){

tempLine.append (inLine.nextToken () + " ");}wordsLine = tempLine.toString ();// Determine new line length.lineLength = wordsLine.length ();outline = new StringBuffer ();// Pad left with half the spaces.for (int ctr = 1 ; ctr <= ((80 – lineLength) / 2) ; ctr++){

outline.append (" ");}outline.append (wordsLine);c.println (outline.toString ());output.println (outline);inputLine = input.readLine ();

}output.close ();c.println ();c.println ("The output file has been written to disk");

} // main method} // C0802 class

Page 44: 6916388 Problems and Solutions in Java

Page 42

Exercise #3

Write a program to read a line of text and change the spelling of words ending in “or” toend in “our”.

Solution

// Chapter #8 - Exercise #3 (C0803.java)// NOTE: The assumption in this program is that a two letter word like// "or" does not end in or.

import java.awt.*;import java.util.*;import hsa.Console;

public class C0803{

static Console c;

static public void main (String args []){

c = new Console ();String inputLine, word, base, lastTwo;StringBuffer outline;int wordLength;// Get a line of text from the user.c.print ("Enter a line of text: ");inputLine = c.readLine ();// Create a Tokenizer to be able to look at each word.StringTokenizer inLine = new StringTokenizer (inputLine);outline = new StringBuffer ();while (inLine.hasMoreTokens ()){

word = inLine.nextToken ();// Watch for 1 letter words that would produce// a substring error.if (word.length () < 3){

outline.append (word + " ");}else{

lastTwo = word.substring (word.length () – 2);// If ending in "or" replace with "our".if (lastTwo.equals ("or")){

base = word.substring (0, word.length () – 2);outline.append (base.concat ("our "));

}

Page 45: 6916388 Problems and Solutions in Java

Page 43

else{

outline.append (word + " ");}

}}c.print ("The new line: ");c.println (outline.toString ());

} // main method} // C0803 class

Page 46: 6916388 Problems and Solutions in Java

Page 44

Exercise #4

Write a program to generate the values for car license plates that consists of three capitalletters, chosen at random, followed by a space and then three digits chosen at random.

Solution

// Chapter #8 - Exercise #4 (C0804.java)

import java.awt.*;import java.util.*;import hsa.Console;

public class C0804{

static Console c;

static public void main (String args []){

c = new Console ();// Set up a string of all uppercase letters.String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";char oneLetter;int letterPtr, numberPtr;c.println ("Ten randomly generated license plate numbers.");c.println ();// Pick and combine letters randomly.for (int ctr = 1 ; ctr <= 10 ; ctr++){

StringBuffer plate = new StringBuffer ();// Append three random letters.for (int inner = 1 ; inner <= 3 ; inner++){

letterPtr = (int) (Math.random () * 26);plate.append (alpha.charAt (letterPtr));

}// Append a space.plate.append (" ");// Append three random digits to the license plate.for (int inner = 1 ; inner <= 3 ; inner++){

numberPtr = (int) (Math.random () * 10);plate.append (Integer.toString (numberPtr));

}c.println (plate.toString ());

}} // main method

} // C0804 class

Page 47: 6916388 Problems and Solutions in Java

Page 45

Chapter 9.16 Solutions

Exercise #1

Write a procedure-type method called compound that has as parameters an amount ofmoney deposited in the bank and an annual compound interest rate, and produces a tableof values of the balance after each year for 10 years. Be sure that the annual balance is keptto the nearest cent. Write a driver program and test the method.

Solution

// Chapter #9 - Exercise #1 (C0901.java)

import java.awt.*;import hsa.Console;

public class C0901{

static Console c;

static public void main (String args []){

c = new Console ();compound (5000, .03, c);

} // main method

// The method compound calculates the new balance and// displays a ten year summary.static public void compound (double amount, double rate, Console c){

c.println ("Years Balance");for (int ctr = 1 ; ctr < 11 ; ctr++){

amount = amount * (1 + rate);c.print (ctr, 3, 0);c.print (" ");c.println (amount, 8, 2);

}} // compound method

} // C0901 class

Page 48: 6916388 Problems and Solutions in Java

Page 46

Exercise #2

Write a procedure-type method called inputInteger that will ask for the input of an integerand store it in the variable that is its only parameter in such a way that, if a real number orstring is input, the procedure does not halt execution but simply asks the user to try again.

Solution

// Chapter #9 - Exercise #2 (C0902.java)// NOTE: This method is written as a function type method instead// of a procedure type, to return the integer value to the program.

import java.awt.*;import hsa.Console;

public class C0902{

static Console c;

static public void main (String args []){

c = new Console ();int value = 1;while (value != 0){

c.print ("Enter an integer (zero to quit): ");value = inputInteger (c);c.println ("You entered " + value);

}} // main method

// The method inputInteger inputs an integer and uses a// try...catch for bad data.static public int inputInteger (Console c){

String temp;int number;while (true){

try{

temp = c.readLine ();number = Integer.parseInt (temp);return number;

}catch (NumberFormatException e){

c.println ("INPUT INVALID, please enter an integer");}

}} // inputInteger method

} // C0902 class

Page 49: 6916388 Problems and Solutions in Java

Page 47

Exercise #3

Write a function-type method called phoneList that accepts as a parameter a name thatconsists of a first and last name, and returns a value that is the last name then the firstwith a comma between. For example, if the value stored in name before calling themethod was “Veena Guru” the value produced by the method would be “Guru, Veena”.

Solution

// Chapter #9 - Exercise #3 (C0903.java)

import java.awt.*;import java.util.*;import hsa.Console;

public class C0903{

static Console c;

static public void main (String args []){

c = new Console ();String name;name = "Veena Guru";c.println ("The current name is " + name);c.println ("The changed name is " + phoneList (name));

} // main method

// phoneList uses a Tokenizer to break up the names and reverse them.static public String phoneList (String name){

StringTokenizer nameIn = new StringTokenizer (name);String firstName = nameIn.nextToken ();String lastName = nameIn.nextToken ();return lastName + ", " + firstName ;

} // phoneList method} // C0903 class

Page 50: 6916388 Problems and Solutions in Java

Page 48

Exercise #4

When a person is buying a house that has a cost c, the money available is a combination ofsavings s, plus a mortgage loan amount m, that can be obtained. The financial institutionfrom which the mortgage loan is to be obtained will establish some borrowing limit b,based on a consideration of the person's salary, credit history, and so on. Write a methodto compute m in terms of c, s, and b. Use the Math methods max and min.

Solution

// Chapter #9 - Exercise #4 (C0904.java)

import java.awt.*;import hsa.Console;

public class C0904{

static Console c;

static public void main (String args []){

c = new Console ();int cost = 182000;int savings = 31500;int borrowLimit = 150000;int mortgageLoan;// Use the method mortgageAmount to calculate mortgageLoan.mortgageLoan = mortgageAmount (cost, savings , borrowLimit);c.println ("The amount of the loan is " + mortgageLoan);

} // main method

// method mortgageAmountstatic public int mortgageAmount (int cst, int s, int b){

int m;m = Math.min (cst – s, b);return Math.max (m, 0);

} // mortgageAmount method} // C0904 class

Page 51: 6916388 Problems and Solutions in Java

Page 49

Exercise #5

Write an implementation of the function-type method based on the recursive definitionof a palindrome that accepts strings containing upper case letters, punctuation, andblanks. The upper case letters are to be converted to lower case, and the punctuation andblanks are to be ignored.

Solution

// Chapter #9 - Exercise #5 (C0905.java)

import java.awt.*;import hsa.Console;

public class C0905{

static Console c;

static public String clean (String s){

String dirt = ",.:;()!'\\* ";StringBuffer t = new StringBuffer ();for (int i = 0 ; i < s.length () ; i++){

if (dirt.indexOf (s.charAt (i)) == –1)t.append (s.charAt (i));

}return t.toString ();

} // clean method

// Method to change string so it contains only lower case letters.static public String lowerCase (String s){

StringBuffer t = new StringBuffer ();char ch;for (int i = 0 ; i < s.length () ; i++){

ch = s.charAt (i);t = t.append (Character.toLowerCase (ch));

}return t.toString ();

} // lowerCase method

static public void main (String args []){

c = new Console ();// Test method testPalindrome.String text;for (int count = 1 ; count <= 3 ; count++)

Page 52: 6916388 Problems and Solutions in Java

Page 50

{c.print ("Enter a line of text: ");text = c.readLine ();if (testPalindrome (text))

c.println (text + " is a palindrome ");else

c.println (text + " is not a palindrome ");}

} // main method

// Recursive method that uses methods clean and lowerCase to// test for palindromes.static public boolean testPalindrome (String s){

String t = lowerCase (clean (s));int tLen = t.length ();if (t.length () > 1)

return (t.charAt (0) == t.charAt (tLen – 1)) && testPalindrome(t.substring (1, tLen – 1));

elsereturn true;

} // testPalindrome method} // C0905 class

Page 53: 6916388 Problems and Solutions in Java

Page 51

Exercise #6

Write a recursive function-type method to compute the alphabetically first character in astring. For the string recursive, the function should return the value c.

Solution

// Chapter #9 - Exercise #6 (C0906.java)

import java.awt.*;import hsa.Console;

public class C0906{

static Console c;

static public void main (String args []){

c = new Console ();String text;c.print ("Enter an string: ");text = c.readLine ();c.println ("The first character, alphabetically is \"" +

alphaFirst (text) + "\"");} // main method

// The method alphaFirst finds the alphabetically first// character in a string.static public char alphaFirst (String s){

if (s.length () == 1) // If only one character,return it.{

return s.charAt (0);}else{

// Compare character to the rest of the string.if (s.charAt (0) < alphaFirst (s.substring (1)))

return s.charAt (0);else

return alphaFirst (s.substring (1));}

} // alphaFirst method} // C0906 class

Page 54: 6916388 Problems and Solutions in Java

Page 52

Exercise #7

Write a non-recursive function-type method to perform the same computation as in theprevious exercise.

Solution

// Chapter #9 - Exercise #7 (C0907.java)

import java.awt.*;import hsa.Console;

public class C0907{

static Console c;

static public void main (String args []){

c = new Console ();String text;c.print ("Enter an string: ");text = c.readLine ();c.println ("The first character, alphabetically is "

+ findFirst (text));} // main method

// The method findFirst finds the alphabetically first// character in a string.static public char findFirst (String s){

char first = s.charAt (0);for (int ctr = 1 ; ctr < s.length () ; ctr++){

// If current character comes before 'first.if (s.charAt (ctr) < first)

first = s.charAt (ctr);}return first;

} // findFirst method} // C0907 class

Page 55: 6916388 Problems and Solutions in Java

Page 53

Exercise #8

A string is a palindrome if the front half is a mirror image of the back half. To say thisanother way, a string is a palindrome if, for each character in the front half of the string,that character is the same as the character in the mirror image position in the back half ofthe string.

This definition suggests another iterative way of checking if a string is a palindrome.Write a method that determines if a string is a palindrome by using a for statement thatexamines each character in the front half of the string and compares it with the characterin the mirror image position in the back half of the string.

Produce two versions of your function. In the first version, assume that the string to bechecked contains only lower case letters. In the second version, assume that the string cancontain upper case letters, punctuation, and blanks. The upper case letters are to beconverted to lower case, and the punctuation and blanks are to be ignored.

Solution

// Chapter #9 - Exercise #8 (C0908.java)

import java.awt.*;import hsa.Console;

public class C0908{

static Console c;

static public String clean (String s){

String dirt = ",.:;()!'\\* ";StringBuffer t = new StringBuffer ();for (int i = 0 ; i < s.length () ; i++){

if (dirt.indexOf (s.charAt (i)) == –1)t.append (s.charAt (i));

}return t.toString ();

} // clean method

// Method to change string so it contains only lower case letters.static public String lowerCase (String s){

StringBuffer t = new StringBuffer ();char ch;for (int i = 0 ; i < s.length () ; i++){

ch = s.charAt (i);t = t.append (Character.toLowerCase (ch));

}return t.toString ();

} // lowerCase method

Page 56: 6916388 Problems and Solutions in Java

Page 54

static public void main (String args []){

c = new Console ();// Read in a line of text.String text;c.print ("Enter a line of text: ");text = c.readLine ();// testPalindromeV1 compares raw text.if (testPalindromeV1 (text))

c.println (text + " is a palindome using version #1 ");else

c.println (text + " is not a palindome using version #1");// testPalindromeV2 cleans garbage and forces lower case.if (testPalindromeV2 (text))

c.println (text + " is a palindome using version #2 ");else

c.println (text + " is not a palindome using version #2");} // main method

// Iterative method tests for palindromes by comparing// the first half of the string to the last half.static public boolean testPalindromeV1 (String s){

int sLen = s.length ();boolean wordTest = true;for (int ctr = 0 ; ctr < sLen / 2 ; ctr++){

if (s.charAt (ctr) != s.charAt (sLen – (1 + ctr)))wordTest = false ;

}return wordTest;

} // testPalindromeV1 method

// Iterative method that uses methods clean and lowerCase to// test for palindromes by comparing the first half of the// string to the last half.static public boolean testPalindromeV2 (String s){

String t = lowerCase (clean (s));int tLen = t.length ();boolean wordTest = true;for (int ctr = 0 ; ctr < tLen / 2 ; ctr++){

if (t.charAt (ctr) != t.charAt (tLen – (1 + ctr)))wordTest = false ;

}return wordTest;

} // testPalindromeV2 method} // C0908 class

Page 57: 6916388 Problems and Solutions in Java

Page 55

Exercise #9

Does the method checkPrime return the proper result for the values 2 and 3? Use tracingto explain your answer.

Solution

The method checkPrime does return the proper result for value 2 and 3, theexplanation follows.

To prove this, let's trace execution for n=2

a. sqrtr = Math.sqrt (n) = Math.sqrt (2) = 1.414...

b. factor = 2

c. while (factor <= sqrtr && n % factor != 0)

becomes while (2 <= 1.414... && 2 % 2 != 0)

becomes while (false && false)

becomes while (false)

which means the loop never executes

d. return factor > sqrtr

becomes return 2 > 1.414...

becomes return true

In other words, the function returns true for n = 2. Now let's trace it

for n=3

a. sqrtr = Math.sqrt (n) = Math.sqrt (3) = 1.71...

b. factor = 2

c. while (factor <= sqrtr && n % factor != 0)

becomes while (2 <= 1.71... && 3 % 2 != 0)

becomes while (false && true)

becomes while (false)

which means the loop never executes

d. return factor > sqrtr

becomes return 2 > 1.71...

becomes return true

Thus the function returns true for n = 2 and n = 3.

Page 58: 6916388 Problems and Solutions in Java

Page 56

Exercise #10

The Cypher class encrypts and decrypts words using the first letter of the keyword for thefirst character in the message, the second letter for the next character, and so on. In thisexample the keyword is ñcodeî.

Message: Is this a test? Yes

Key word string: codecodecodecodecod

This means that when the user enters a message to decrypt, the spacing and punctuationmust be exactly right or the message will not decrypt properly. Modify the Cypher class byhaving the place in the key word only increased when used to encrypt a letter.

Message Is this a test? Yes

Key word string: co deco d ecod eco

Solution

Only the encryptedMessage and decryptedMessage methods of the Cypher programneed be changed.

public static String encryptedMessage (String message, String keyword){

int keywordLetter = 0;StringBuffer answer = new StringBuffer ();

for (int i = 0 ; i < message.length () ; i++){

char chToEncrypt = message.charAt (i);char ch = encryptedLetter (chToEncrypt,

keyword.charAt (keywordLetter));// Only advance keyword letter position if the character to be// encrypted was a letter.if ((('A' <= chToEncrypt) && (chToEncrypt <= 'Z')) ||

(('a' <= chToEncrypt) && (chToEncrypt <= 'z'))){

keywordLetter = (keywordLetter + 1) % keyword.length ();}answer.append (ch);

}return answer.toString ();

} // encryptedMessage method

public static String decryptedMessage (String message, String keyword){

int keywordLetter = 0;StringBuffer answer = new StringBuffer ();

for (int i = 0 ; i < message.length () ; i++){

char chToDecrypt = message.charAt (i);char ch = decryptedLetter (chToDecrypt,

keyword.charAt (keywordLetter));

Page 59: 6916388 Problems and Solutions in Java

Page 57

// Only advance keyword letter position if the character to be// decrypted was a letter.if ((('A' <= chToDecrypt) && (chToDecrypt <= 'Z')) ||

(('a' <= chToDecrypt) && (chToDecrypt <= 'z'))){

keywordLetter = (keywordLetter + 1) % keyword.length ();}answer.append (ch);

}return answer.toString ();

} // decryptedMessage method

Page 60: 6916388 Problems and Solutions in Java

Page 58

Exercise #11

A great deal of information can be derived from a message’s word breaks, punctuation,and letter case. Modify the Cypher class so that it outputs the encrypted message withoutany punctuation in blocks of five letters, all in lower case.

Message Is this a test? Yes

Key word string: co deco d ecod eco

Encrypted: Kg wlkg d xggw? Cgg

Modified: kgwlk gdxgg wcgg

Solution

Only the encryptedMessage, decryptedMessage and encryptedLetter methods of theCypher program need be changed.

public static char encryptedLetter (char letterToEncrypt, char key){

int keyCode = (int) key – (int) 'a';int encryptedLetterCode;

// letterToEncrypt must be a-z or A-Z.if (('A' <= letterToEncrypt) && (letterToEncrypt <= 'Z')){

letterToEncrypt = (char) ((int) letterToEncrypt – (int) 'A' + (int) 'a');}

encryptedLetterCode = (int) letterToEncrypt + keyCode;if (encryptedLetterCode > (int) 'z'){

encryptedLetterCode –= 26;}return (char) encryptedLetterCode;

} // encryptedLetter method

public static String encryptedMessage (String message, String keyword){

int keywordLetter = 0;int answerLetter = 0;StringBuffer answer = new StringBuffer ();

for (int i = 0 ; i < message.length () ; i++){

char chToEncrypt = message.charAt (i);char ch = encryptedLetter (chToEncrypt,

keyword.charAt (keywordLetter));if ((('A' <= chToEncrypt) && (chToEncrypt <= 'Z')) ||

(('a' <= chToEncrypt) && (chToEncrypt <= 'z'))){

Page 61: 6916388 Problems and Solutions in Java

Page 59

keywordLetter = (keywordLetter + 1) % keyword.length ();answerLetter = (answerLetter + 1) % 5;answer.append (ch);if (answerLetter == 0){

answer.append (' ');}

}}return answer.toString ();

} // encryptedMessage method

public static String decryptedMessage (String message, String keyword){

int keywordLetter = 0;StringBuffer answer = new StringBuffer ();

for (int i = 0 ; i < message.length () ; i++){

char chToDecrypt = message.charAt (i);char ch = decryptedLetter (chToDecrypt,

keyword.charAt (keywordLetter));if ((('A' <= chToDecrypt) && (chToDecrypt <= 'Z')) ||

(('a' <= chToDecrypt) && (chToDecrypt <= 'z'))){

keywordLetter = (keywordLetter + 1) % keyword.length ();}answer.append (ch);

}return answer.toString ();

} // decryptedMessage method

Page 62: 6916388 Problems and Solutions in Java

Page 60

Chapter 10.10 Solutions

Exercise #1

Instantiate an object from the Turtle class and use its methods to write a method to drawa square with its upper-left corner at (xc, yc) and of size size in color clr. The signature ofthis procedure will be

square (int xc, int yc, int size, Color clr);

It must, of course, be a part of a program that imports the Turtle class. Now write aprogram that uses square to draw 100 random-sized red squares, located with upper-leftcorners at random points in the window.

Solution

// Chapter #10 - Exercise #1 (C1001.java)// Note: Requires the Turtle class. If the Turtle class is in the// current directory then remove the "import hsa.book.Turtle;" line.

import java.awt.*;import hsa.Console;import hsa.book.Turtle;

public class C1001{

static Turtle t;static Console c;

static public void main (String args []){

c = new Console ();t = new Turtle (c);int x, y, size;// Loop to generate the 100 squares.for (int sqCtr = 1 ; sqCtr <= 100 ; sqCtr++){

x = (int) (Math.random () * 600 + 1);y = (int) (Math.random () * 350 + 50);size = (int) (Math.random () * 100 + 25);square (x, y, size, Color.red);

}} // main method

// Draws a red square at xc,yc.static public void square (int xc, int yc, int size, Color clr){

t.setColor (clr);t.setPosition (xc, yc);t.showTrace ();

Page 63: 6916388 Problems and Solutions in Java

Page 61

for (int side = 1 ; side <= 4 ; side++){

t.move (size);t.turnRight (90);

}} // square method

} // C1001 class

Page 64: 6916388 Problems and Solutions in Java

Page 62

Exercise #2

Using the Turtle class, write a method to draw a moon similar to that drawn in thischapter with a center at (xc, yc) made up of squares of size size in color clr. The signatureof the moon method should be

moon (int xc, int yc, int size, Color clr);

Draw 20 moons of random size at random points in the window.

Solution

// Chapter #10 - Exercise #2 (C1002.java)// Note: Requires the Turtle class. If the Turtle class is in the// current directory then remove the "import hsa.book.Turtle;" line.

import java.awt.*;import hsa.Console;import hsa.book.Turtle;

public class C1002{

static Turtle t;static Console c;

static public void main (String args []){

c = new Console ();t = new Turtle (c);int x, y, size;t.setAngle (0);// Loop to generate the 20 moons.for (int sqCtr = 1 ; sqCtr <= 20 ; sqCtr++){

x = (int) (Math.random () * 600 + 1);y = (int) (Math.random () * 350 + 50);size = (int) (Math.random () * 100 + 25);moon (x, y, size, Color.green);

}} // main method

// Draws a moon at xc,yc.static public void moon (int xc, int yc, int size, Color clr){

t.setColor (clr);t.setPosition (xc, yc);t.showTrace ();for (int sqCtr = 1 ; sqCtr <= 36 ; sqCtr++){

for (int side = 1 ; side <= 4 ; side++){

Page 65: 6916388 Problems and Solutions in Java

Page 63

t.move (size);t.turnRight (90);

}t.turnRight (10);

}} // moon method

} // C1002 class

Page 66: 6916388 Problems and Solutions in Java

Page 64

Exercise #3

Use an object instantiated from the Turtle class to draw a simple house with a peaked roofand a window as shown in Figure 10.5.

Figure 10.5 Picture of House

Make the house drawing into a method and use it in a main method to draw a row ofhouses across the bottom of the window. Modify the program to draw a series of suchrows. Arrange that as the rows move from the bottom to the top of the window thehouses get smaller, to create the illusion of distance.

Solution

// Chapter #10 - Exercise #3 (C1003.java)// Note: Requires the Turtle class. If the Turtle class is in the// current directory then remove the "import hsa.book.Turtle;" line.

import java.awt.*;import hsa.Console;import hsa.book.Turtle;

public class C1003{

static Turtle t;static Console c;

static public void main (String args []){

c = new Console ();t = new Turtle (c);int y = 400;int width;// Outer loop draws one row of houses per iteration.// Each successive loop draws more and smaller houses.for (int outer = 1 ; outer <= 5 ; outer++){

width = 60 – (outer * 10);// Inner loop draws one house per iteration.for (int inner = 1 ; inner < 8 ; inner++){

house (inner * 75 – 25 – width / 2, y,width, Color.blue);

Page 67: 6916388 Problems and Solutions in Java

Page 65

}y –= width * 1.5 + 20;

}} // main method

// Draws a house.static public void house (int xc, int yc, int size, Color clr){

t.setColor (clr);t.setPosition (xc, yc);t.showTrace ();t.move (size);t.turnLeft (90);t.move (size);t.turnLeft (45);t.move ((int) (size / Math.sqrt (2)));t.turnLeft (90);t.move ((int) (size / Math.sqrt (2)));t.turnLeft (45);t.move (size);t.turnRight (180);t.hideTrace ();t.move ((int) (size * .75));t.turnRight (90);t.move ((int) (size * .333));t.showTrace ();for (int ctr = 1 ; ctr <= 4 ; ctr++){

t.move ((int) (size * .333));t.turnRight (90);

}} // house method

} // C1003 class

Page 68: 6916388 Problems and Solutions in Java

Page 66

Exercise #4

Use the class FatTurtle to instantiate three turtles to draw in the three primary colors:blue, yellow, and red. Start each turtle at a different spot on the screen then have eachmake 25 moves of distance 5 pixels randomly in one of the four directions: left or right,up or down. Have them move ñsimultaneouslyî, that is, the blue making one randommove, then the yellow, then the red.

Solution

// Chapter #10 - Exercise #4 (C01004.java)// Note: Requires the FatTurtle class. If the FatTurtle class is in the// current directory then remove the "import hsa.book.FatTurtle;" line.// Note: Try increasing the stepSize from 5 pixels to larger numbers// for a better visual effect.

import java.awt.*;import hsa.Console;import hsa.book.FatTurtle;

public class C1004{

static FatTurtle ftBlue, ftYellow, ftRed;static Console c;

static public void main (String args []){

c = new Console ();int x, y, direction, stepSize;stepSize = 5;// Create three fatTurtles and set their colours.ftBlue = new FatTurtle (c);ftBlue.setColor (Color.blue);ftBlue.setLineWidth (2);ftYellow = new FatTurtle (c);ftYellow.setColor (Color.yellow);ftYellow.setLineWidth (3);ftRed = new FatTurtle (c);ftRed.setColor (Color.red);ftRed.setLineWidth (4);// Randomly set starting positions of each turtle.x = (int) (Math.random () * 400 + 100);y = (int) (Math.random () * 300 + 100);ftBlue.setPosition (x, y);x = (int) (Math.random () * 400 + 100);y = (int) (Math.random () * 300 + 100);ftYellow.setPosition (x, y);x = (int) (Math.random () * 400 + 100);y = (int) (Math.random () * 300 + 100);ftRed.setPosition (x, y);

Page 69: 6916388 Problems and Solutions in Java

Page 67

// Move each turtle in random directions 25 times.for (int moves = 1 ; moves <= 25 ; moves++){

direction = 90 * (int) (Math.random () * 4);ftBlue.setAngle (direction);// Move 5 pixels.ftBlue.move (stepSize);direction = 90 * (int) (Math.random () * 4);ftYellow.setAngle (direction);// Move 5 pixels.ftYellow.move (stepSize);direction = 90 * (int) (Math.random () * 4);ftRed.setAngle (direction);// Move 5 pixels.ftRed.move (stepSize);

}} // main method

} // C1004 class

Page 70: 6916388 Problems and Solutions in Java

Page 68

Exercise #5

Use the class FatTurtle to create a window with horizontal stripes. Have 10 stripes fillingthe window and alternate the colors from one stripe to the next. Make this into a methodthat will produce alternating stripes of any two colors with the number of stripes fillingthe window specified as a parameter. The signature of the method is

stripes (int number, Color clr1, Color clr2);

Solution

// Chapter #10 - Exercise #5 (C1005.java)// Note: Requires the FatTurtle class. If the FatTurtle class is in the// current directory then remove the "import hsa.book.FatTurtle;" line.

import java.awt.*;import hsa.Console;import hsa.book.FatTurtle;

public class C1005{

static FatTurtle ft;static Console c;

static public void main (String args []){

c = new Console ();int number;// Create fatTurtle.ft = new FatTurtle (c);c.print ("Enter a number of stripes: ");number = c.readInt ();drawStripes (number, Color.red, Color.blue);

} // main method

static public void drawStripes (int nStripes, Color clr1, Color clr2){

// Determine width of one stripe and set line to that width.int width = c.maxy () / nStripes;ft.setLineWidth (width);// Set vertical position to zero (top of screen).int yValue = width / 2;for (int ctr = 1 ; ctr <= nStripes ; ctr++){

// Use mod to determine the colour of the alternating stripes.if (ctr % 2 == 1)

ft.setColor (clr1);else

ft.setColor (clr2);

Page 71: 6916388 Problems and Solutions in Java

Page 69

// Start each stripe at the left, facing to the right.ft.setAngle (0);// The setPosition uses yValue to move down the screen.ft.setPosition (0, yValue);//Draw the coloured line.ft.move (c.maxx ());yValue += width;

}} // drawStripes method

} // C1005 class

Page 72: 6916388 Problems and Solutions in Java

Page 70

Exercise #6

Use the class FatTurtle to instantiate two turtles, one of which will draw horizontal stripes,the other the same number of vertical stripes. Program the two turtles to drawñsimultaneouslyî, the first in red and white, the second in green and yellow.

Solution

// Chapter #10 - Exercise #6 (C1006.java)// Note: Requires the FatTurtle class. If the FatTurtle class is in the// current directory then remove the "import hsa.book.FatTurtle;" line.// Note: There are many variations possible here, experiment with order of// drawing, direction, and colours.

import java.awt.*;import hsa.Console;import hsa.book.FatTurtle;

public class C1006{

static FatTurtle ft1, ft2;static Console c;

static public void main (String args []){

c = new Console ();int number;// Create fatTurtles.ft1 = new FatTurtle (c);ft2 = new FatTurtle (c);c.print ("Enter a number of stripes: ");number = c.readInt ();draw2Stripes (number, Color.red, Color.blue, Color.green,

Color.yellow);} // main method

static public void draw2Stripes (int nStripes, Color clr1, Color clr2,Color clr3, Color clr4)

{// Determine width of one horizontal stripe and set// line to that width.int hWidth = c.maxy () / nStripes;ft1.setLineWidth (hWidth);// Set vertical position to zero (top of screen).int yValue = hWidth / 2;// Determine width of one vertical stripe and set line to that width.int vWidth = c.maxx () / nStripes;ft2.setLineWidth (vWidth);// Set horizontal position to zero (left of screen).int xValue = vWidth / 2;for (int ctr = 1 ; ctr <= nStripes ; ctr++)

Page 73: 6916388 Problems and Solutions in Java

Page 71

{// Use mod to determine the colour of the alternating stripes.if (ctr % 2 == 1){

ft1.setColor (clr1);ft2.setColor (clr3);

}else{

ft1.setColor (clr2);ft2.setColor (clr4);

}// Draw a horizontal stripe.ft1.setAngle (0);ft1.setPosition (0, yValue);ft1.move (c.maxx ());yValue += hWidth;// Draw a vertical stripe.ft2.setAngle (270);ft2.setPosition (xValue, 0);ft2.move (c.maxy ());xValue += vWidth;

}} // draw2Stripes method

} // C1006 class

Page 74: 6916388 Problems and Solutions in Java

Page 72

Exercise #7

Use the class FatTurtle to write a method to draw regular polygons of n sides in lines ofwidth with the center at (xc, yc) and size (distance from center to any vertex) size. Itssignature would be

polygon (int xc, int yc, int size, int width, Color clr);

Use the method polygon to approximate a circle by using as large a number of sides n aspractical.

Solution

// Chapter #10 - Exercise #7 (C1007.java)// Note: Requires the FatTurtle class. If the FatTurtle class is in the// current directory then remove the "import hsa.book.FatTurtle;" line.// Note: The number of sides has been added as a method parameter.

import java.awt.*;import hsa.Console;import hsa.book.FatTurtle;

public class C1007{

static Console c;static FatTurtle turtle1;

static public void main (String args []){

c = new Console ();// Number of polygon sides.int numSides;c.print ("Enter the number of sides: ");numSides = c.readInt ();turtle1 = new FatTurtle (c);polygon (numSides, c.maxx () / 2, c.maxy () / 2, 100, 3, Color.red);

} // main method

// Note: This signature adds one parameter (the number of sides).// This makes the method work as a standalone component.static public void polygon (int sides, int xc, int yc, int size,

int width, Color clr){

// Determine the turning angle for going from side to side.int nAngle = 180 – ((sides – 2) * 180 / sides);double sAngle = 360 / sides;// Use the cosine law to calculate the length of one// side of the polygon.int moveSize = (int) Math.round ((Math.sqrt (2 * size * size –

2 * size * size * Math.cos (sAngle * Math.PI / 180))));

Page 75: 6916388 Problems and Solutions in Java

Page 73

// Select drawing width.turtle1.setLineWidth (width);// Hide the trace and move from the center to the outside.turtle1.hideTrace ();turtle1.setPosition (xc, yc);turtle1.setColor (clr);turtle1.setAngle (270 – nAngle / 2);turtle1.move (moveSize);// The first line will go from left to right horizontally.turtle1.setAngle (0);turtle1.showTrace ();// Draw one side then use the turning angle.for (int ctr = 0 ; ctr < sides ; ctr++){

turtle1.move (moveSize);turtle1.turnLeft (nAngle);

}} // polygon method

} // C1007 class

Page 76: 6916388 Problems and Solutions in Java

Page 74

Exercise #8

Create a class called TurtleDash that inherits from the Turtle but which draws all lines asinterrupted (dashed) lines rather than continuous lines. Use the class to instantiate aturtle and draw a blue dashed square of size getHeight / 4.

Solution

// Chapter #10 - Exercise #8 (C1008.java)// Note: Uses the TurtleDash class.

import java.awt.*;import hsa.Console;

public class C1008{

static TurtleDash td;static Console c;

static public void main (String args []){

c = new Console ();// Create TurtleDash object.td = new TurtleDash (c);// td settings.int moveAmt = c.maxy () / 4;td.setColor (Color.blue);td.setAngle (0);// Draw the square.for (int ctr = 1 ; ctr <= 4 ; ctr++){

td.move (moveAmt);td.turnRight (90);

}} // main method

} // C1008 class

TurtleDash.java

// The "TurtleDash" class extends Turtle to allow drawing with a dashed// line. Note: Requires the Turtle class. If the Turtle class is in the// current directory then remove the "import hsa.book.Turtle;" line.

import java.awt.*;import hsa.Console;import hsa.book.Turtle;

public class TurtleDash extends Turtle{

public TurtleDash (Console c){

Page 77: 6916388 Problems and Solutions in Java

Page 75

super (c);} // constructor method

public void move (int distance){

int newx = 0, newy = 0;double rAngle = (angle * Math.PI) / 180;if (showing){

c.setColor (clr);for (int ctr = 1 ; ctr <= 8 ; ctr++){

newx = (int) Math.round (x + Math.cos (rAngle) *(distance / 16));

newy = (int) Math.round (y + Math.sin (rAngle) *(distance / 16));

showTrace ();c.drawLine (x, y, newx, newy);x = newx;y = newy;newx = (int) Math.round (x + Math.cos (rAngle) *

(distance / 16));newy = (int) Math.round (y + Math.sin (rAngle) *

(distance / 16));x = newx;y = newy;setPosition (x, y);

}}x = newx;y = newy;

} // move method} // TurtleDash class

Page 78: 6916388 Problems and Solutions in Java

Page 76

Chapter 11.12 Solutions

Exercise #1

Write an applet that will produce a table showing the balance in a bank account at the endof each year if an interest rate of 10% a year is credited at the end of each year. In the tableshow the year, starting in 1998 when $1,000.00 is deposited, the interest for the year, andthe balance at the end of the year for 10 years. You will need to display the output usingthe drawString method of the Graphics class.

Solution

// Chapter #11 - Exercise #1 (C1101.java)// Run in 300x300 applet window.

import java.awt.*;import java.applet.Applet;

public class C1101 extends Applet{

double interest, balance;final double RATE = .10;

// Processing and output occur in the paint method in this example.public void paint (Graphics g){

interest = 0.00;balance = 1000.00;g.drawString ("Ten year investment of $1,000.00 at 10%", 20, 10);g.drawString ("Year", 20, 30);g.drawString ("Interest", 80, 30);g.drawString ("Balance", 140, 30);int y = 50;for (int yearCtr = 1998 ; yearCtr < 2008 ; yearCtr++){

interest = balance * RATE;balance += interest;// The "" + yearCtr converts yearCtr into a String.g.drawString ("" + yearCtr, 20, y);g.drawString ("" + round2 (interest), 80, y);g.drawString ("" + round2 (balance), 140, y);y += 20;

}} // paint method

Page 79: 6916388 Problems and Solutions in Java

Page 77

// This method is used to round the balance to 2 decimal places.public double round2 (double value){

value *= 100;long tempValue = Math.round (value);value = tempValue / 100.0;return value;

} // round2 method} // C1101 class

Page 80: 6916388 Problems and Solutions in Java

Page 78

Exercise #2

Write an applet which produces the same table as Exercise 1 but asks the user to enter thestarting year, the initial deposit, the interest rate, and the number of years the table is todisplay. You will need to create labelled TextFields for each input item and a button toinitialize the calculation once the data has been entered.

Solution

// Chapter #11 - Exercise #2 (C1102.java)// NOTE: This applet uses the default FlowLayout layout manager. Use the// mouse to adjust the applet frame if the GUI objects do not// line up correctly.

import java.awt.*;import java.applet.Applet;

public class C1102 extends Applet{

int startYear, numberOfYears;double amount, interest, balance;double rate;TextField txtStartYear, txtDeposit, txtRate, txtNumberOfYears;Label lblStartYear, lblDeposit, lblRate, lblNumberOfYears;Button btnCalc, btnClear;Double d;boolean showCalc;

// Set up the GUI interface.public void init (){

// Create the labels for each of the text fields.lblStartYear = new Label ("Start Year");lblDeposit = new Label ("Deposit ");lblRate = new Label ("Rate(Decimal)");lblNumberOfYears = new Label ("# Years");// Create the text fields.txtStartYear = new TextField (6);txtDeposit = new TextField (8);txtRate = new TextField (6);txtNumberOfYears = new TextField (4);// Create the two buttons.btnCalc = new Button ("Calculate");btnClear = new Button (" Clear ");// Place all the GUI elements one at a time from left to right.// The applet surface should be just wide enough (400 pixels)// that the layout goes to the second line starting with// the txtStartYear text field.add (lblStartYear);add (lblDeposit);add (lblRate);

Page 81: 6916388 Problems and Solutions in Java

Page 79

add (lblNumberOfYears);add (btnCalc);add (txtStartYear);add (txtDeposit);add (txtRate);add (txtNumberOfYears);add (btnClear);showCalc = false ;

} // init method

public void paint (Graphics g){

if (showCalc){

int year = startYear + 1;int y = 100;g.drawString ("Year", 20, 80);g.drawString ("Interest", 80, 80);g.drawString ("Balance", 140, 80);while (year <= startYear + numberOfYears){

interest = balance * rate;balance += interest;// The "" + yearCtr converts yearCtr into a String.g.drawString ("" + year, 20, y);g.drawString ("" + round2 (interest), 80, y);g.drawString ("" + round2 (balance), 140, y);y += 20;year++;

}}

} // paint method

public double round2 (double value){

value *= 100;long tempValue = Math.round (value);value = tempValue / 100.0;return value;

} // round2 method

// Respond to action of user.public boolean action (Event e, Object o){

if (e.target instanceof Button){

if (e.target == btnCalc){

startYear = Integer.parseInt (txtStartYear.getText ());d = Double.valueOf (txtDeposit.getText ());balance = d.doubleValue ();

Page 82: 6916388 Problems and Solutions in Java

Page 80

d = Double.valueOf (txtRate.getText ());rate = d.doubleValue ();numberOfYears = Integer.parseInt

(txtNumberOfYears.getText ());showCalc = true;

}else{

txtStartYear.setText ("");txtDeposit.setText ("");txtRate.setText ("");txtNumberOfYears.setText ("");showCalc = false ;

}// This erases the screen, removing any previous calculations.repaint ();

}return true;

} // action method} // C1102 class

Page 83: 6916388 Problems and Solutions in Java

Page 81

Exercise #3

Write an applet with a panel containing two buttons, one labelled Ball and the otherBlock, and a canvas on which either a ball or a square block is drawn depending on whichbutton is clicked. Arrange to erase the previous drawing each time a button is clicked.

Solution

// Chapter #11 - Exercise #3 (C1103.java)

import java.applet.Applet;import java.awt.*;

public class C1103 extends Applet{

// Instance variables.boolean dBall, dBlock;Button btnBall, btnBlock;

public boolean action (Event e, Object o){

// Determine if a button was pressed.if (e.target instanceof Button){

// Set boolean variables to indicate which button is pressed.if (e.target == btnBall){

dBall = true;dBlock = false ;

}else{

dBall = false ;dBlock = true;

}// Repaint calls paint to update the screen.repaint ();

}return true;

} // action method

public void init (){

// Body of init method.Panel p;btnBall = new Button ("Ball");btnBlock = new Button ("Block");

Page 84: 6916388 Problems and Solutions in Java

Page 82

// The two buttons are added to a panel.p = new Panel ();p.add (btnBall);p.add (btnBlock);// The panel gets added to the screen.add (p);

} // init method

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;int xc = appletWidth / 2;int yc = appletHeight / 2;if (dBall) // draw a ball{

drawBall (g, xc, yc + 20, Math.min (xc, yc – 30), Color.red);}if (dBlock) // draw a rectangle{

g.setColor (Color.blue);g.fillRect (20, 40, appletWidth – 40, appletHeight – 60);

}} // paint method

public void drawBall (Graphics g, int x, int y, int radius , Color clr){

g.setColor (clr);g.fillOval (x – radius, y – radius , 2 * radius, 2 * radius);

} // drawBall method} // C1103 class

Page 85: 6916388 Problems and Solutions in Java

Page 83

Exercise #4

Modify the applet of Exercise 3 to have a second panel with radio buttons to control thecolor of the ball or block drawn.

Solution

// Chapter #11 - Exercise #4 (C1104.java)

import java.applet.Applet;import java.awt.*;

public class C1104 extends Applet{

// Instance variables.private Button btnBall, btnBlock;private Checkbox rdbBlue, rdbRed, rdbGreen;private Color clr = Color.red;boolean dBall, dBlock;

public boolean action (Event e, Object o){

// Determine if a button was pressed.if (e.target instanceof Button){

// Set boolean variables to indicate which button is pressed.if (e.target == btnBall){

dBall = true;dBlock = false ;

}else{

dBall = false ;dBlock = true;

}// Repaint calls paint to update the screen.repaint ();

}if (e.target instanceof Checkbox){

if (rdbBlue.getState () == true)clr = Color.blue;

else if (rdbRed.getState () == true)clr = Color.red;

elseclr = Color.green;

}return true;

} // action method

Page 86: 6916388 Problems and Solutions in Java

Page 84

public void init (){

// Body of init method.Panel pButton, pRadio;CheckboxGroup style;btnBall = new Button ("Ball");btnBlock = new Button ("Block");// Set up the colour radio buttons.style = new CheckboxGroup ();rdbBlue = new Checkbox ("Blue", style, true);rdbRed = new Checkbox ("Red", style, true);rdbGreen = new Checkbox ("Green", style, true);// The two buttons are added to a panel.pButton = new Panel ();pButton.add (btnBall);pButton.add (btnBlock);// The radio button panel for colour is set up.pRadio = new Panel ();pRadio.add (rdbBlue);pRadio.add (rdbRed);pRadio.add (rdbGreen);// The panels get added to the screen.add (pButton);add (pRadio);

} // init method

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;int xc = appletWidth / 2;int yc = appletHeight / 2;if (dBall) // draw a ball{

drawBall (g, xc, yc + 20, Math.min (xc, yc – 30), clr);}if (dBlock) // draw a rectangle{

g.setColor (clr);g.fillRect (20, 40, appletWidth – 40, appletHeight – 60);

}} // paint method

public void drawBall (Graphics g, int x, int y, int radius , Color clr){

g.setColor (clr);g.fillOval (x – radius, y – radius , 2 * radius, 2 * radius);

} // drawBall method} // C1104 class

Page 87: 6916388 Problems and Solutions in Java

Page 85

Exercise #5

Test the BorderLayout manager by adding buttons labelled North on the north position,one labelled East in the east position, and so on. Repeat the exercise using two panels, onein the north position and one in the south position.

Solution A

// Chapter #11 - Exercise #5 (C1105.java)

import java.applet.Applet;import java.awt.*;

public class C1105 extends Applet{

// Instance variables.private Button btnNorth, btnSouth, btnEast, btnWest;private Canvas c;private Graphics displayG;int yLoc = 30;

public boolean action (Event e, Object o){

// Determine if a button was pressed.if (e.target instanceof Button){

// Display a message to indicate what button was pressed.if (e.target == btnNorth)

displayG.drawString ("You pressed the North button",30, yLoc);

else if (e.target == btnEast)displayG.drawString ("You pressed the East button",

30, yLoc);else if (e.target == btnSouth)

displayG.drawString ("You pressed the South button",30, yLoc);

elsedisplayG.drawString ("You pressed the West button",

30, yLoc);// Update y location for the next line.yLoc += 20;

}return true;

} // action method

public void init (){

// Body of init method.btnNorth = new Button ("North");btnSouth = new Button ("South");btnEast = new Button ("East");btnWest = new Button ("West");

Page 88: 6916388 Problems and Solutions in Java

Page 86

// Set the layout to BorderLayout.setLayout (new BorderLayout ());// Add the buttons to the appropriate sections of the BorderLayout.add ("North", btnNorth);add ("South", btnSouth);add ("East", btnEast);add ("West", btnWest);c = new Canvas ();c.resize (200, 300);add ("Center", c);displayG = c.getGraphics ();

} // init method} // C1105 class

Solution B

// Chapter #11 - Exercise #5a (C1105a.java)

import java.applet.Applet;import java.awt.*;

public class C1105a extends Applet{

// Instance variables.private Button btnNorth, btnSouth;private Panel panelNorth, panelSouth;private Canvas c;private Graphics displayG;int yLoc = 30;

public boolean action (Event e, Object o){

// Determine if a button was pressed.if (e.target instanceof Button){

// Display a message to indicate what button was pressed.if (e.target == btnNorth)

displayG.drawString ("You pressed the North button",30, yLoc);

elsedisplayG.drawString ("You pressed the South button",

30, yLoc);// Update y location for the next line.yLoc += 20;

}return true;

} // action method

Page 89: 6916388 Problems and Solutions in Java

Page 87

public void init (){

// Body of init method.// Placing the buttons in panels makes the buttons// shrink to their "natural" size.btnNorth = new Button ("North");panelNorth = new Panel ();panelNorth.add (btnNorth);btnSouth = new Button ("South");panelSouth = new Panel ();panelSouth.add (btnSouth);// Set the layout to BorderLayout.setLayout (new BorderLayout ());// Add the panels to the appropriate sections of the BorderLayout.add ("North", panelNorth);add ("South", panelSouth);c = new Canvas ();c.resize (200, 300);add ("Center", c);displayG = c.getGraphics ();

} // init method} // C1105a class

Page 90: 6916388 Problems and Solutions in Java

Page 88

Exercise #6

Test the FlowLayout default manager by adding several text fields of different lengths inthe applet. Change the lengths of the fields to see what happens.

Solution

// Chapter #11 - Exercise #6 (C1106.java)import java.applet.Applet;import java.awt.*;

public class C1106 extends Applet{

// Set up the GUI interface.public void init (){

TextField txt1, txt2, txt4, txt8, txt16, txt32;// Create some text fields.txt1 = new TextField ("1", 1);txt2 = new TextField ("22", 2);txt4 = new TextField ("4444", 4);txt8 = new TextField ("88888888", 8);txt16 = new TextField ("16", 16);txt32 = new TextField ("32", 32);add (txt1);add (txt2);add (txt4);add (txt8);add (txt16);add (txt32);

} // init method} // C1106 class

Page 91: 6916388 Problems and Solutions in Java

Page 89

Exercise #7

Create an applet to show the animation of red circles radiating from the center of a canvasuntil they touch the border of the canvas, then starting again from the center.

Solution

// Chapter #11 - Exercise #7 (C1107.java)

import java.applet.Applet;import java.awt.*;

public class C1107 extends Applet{

final int DELAY_TIME = 1500000;

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;int xc = appletWidth / 2;int yc = appletHeight / 2;int radius = 20;for (int loopCtr = 0 ; loopCtr < 10 ; loopCtr++){

while ((xc > radius) && (yc > radius)){

g.setColor (Color.white);g.fillRect (0, 0, appletWidth, appletHeight);g.setColor (Color.red);g.drawOval (xc – radius, yc – radius,

radius * 2, radius * 2);delay (DELAY_TIME);radius += 20;

}g.setColor (Color.white);g.fillRect (0, 0, appletWidth, appletHeight);delay (DELAY_TIME);radius = 20;

}} // paint method

public void delay (int howLong){

// This wastes time.for (int i = 1 ; i <= howLong ; i++){

double garbage = Math.PI * Math.PI;}

} // delay method} // C1107 class

Page 92: 6916388 Problems and Solutions in Java

Page 90

Exercise #8

Change the applet of Exercise 7 so that you do not erase the circle as it moves out butwhen it reaches the border and starts over from the center.

Solution

// Chapter #11 - Exercise #8 (C1108.java)

import java.applet.Applet;import java.awt.*;

public class C1108 extends Applet{

final int DELAY_TIME = 1500000;

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;int xc = appletWidth / 2;int yc = appletHeight / 2;int radius = 20;for (int loopCtr = 0 ; loopCtr < 10 ; loopCtr++){

while ((xc > radius) && (yc > radius)){

g.setColor (Color.red);g.drawOval (xc – radius, yc – radius,

radius * 2, radius * 2);delay (DELAY_TIME);radius += 20;

} // whileg.setColor (Color.white);g.fillRect (0, 0, appletWidth, appletHeight);delay (DELAY_TIME);radius = 20;

} // for} // paint method

public void delay (int howLong){

// This wastes time.for (int i = 1 ; i <= howLong ; i++){

double garbage = Math.PI * Math.PI;}

} // delay method} // C1108 class

Page 93: 6916388 Problems and Solutions in Java

Page 91

Exercise #9

Write an applet to show the animation of a ball starting at the center of its canvas andmoving randomly in any of the four directions: north, south, east, and west by a smallamount until it reaches the border of the canvas, then starting over. Try not erasing theimage so as to produce a zigzag trail.

Solution

// Chapter #11 - Exercise #9 (C1109.java)// NOTE: This applet uses a drawing surface of at least 400x400// pixels in size. When the applet is first run, choose a 400x400// applet size. If you are running it a second time, choose// “Run with Args" to set the applet size.

import java.applet.Applet;import java.awt.*;

public class C1109 extends Applet{

final int DELAY_TIME = 50000;final int RADIUS = 20;int x, y, direction, colorVal;Color clr = Color.blue;

public void drawBall (Graphics g, int x, int y, int radius , Color clr){

g.setColor (clr);g.fillOval (x – radius, y – radius , 2 * radius, 2 * radius);g.setColor (Color.black);g.drawOval (x – radius, y – radius, 2 * radius, 2 * radius);

} // drawBall method

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;// Draw the pattern ten times.for (int loopCtr = 0 ; loopCtr < 10 ; loopCtr++){

while ((RADIUS <= x) && (x <= appletWidth – RADIUS) &&(RADIUS <= y) && (y <= appletHeight – RADIUS))

{drawBall (g, x, y, RADIUS, Color.green);direction = (int) (Math.random () * 4);if (direction == 0)

y –= 10;else if (direction == 1)

x += 10;else if (direction == 2)

y += 10;

Page 94: 6916388 Problems and Solutions in Java

Page 92

elsex –= 10;

// Pause to allow the pattern to be viewed.delay (DELAY_TIME);

}// Start the ball in the center of the applet.x = appletWidth / 2;y = appletHeight / 2;// Use fillRect to erase the background.g.setColor (Color.white);g.fillRect (0, 0, appletWidth, appletHeight);

}} // paint method

public void delay (int howLong){

// This wastes time.for (int i = 1 ; i <= howLong ; i++){

double garbage = Math.PI * Math.PI;}

} // delay method} // C1109 class

Page 95: 6916388 Problems and Solutions in Java

Page 93

Exercise #10

Modify the applet of Exercise 9 so that the color of the ball changes randomly amongthree different colors, each time it starts from the center. Follow the animation for 10starts from the center.

Solution

// Chapter #11 - Exercise #10 (C1110.java)

import java.applet.Applet;import java.awt.*;

public class C1110 extends Applet{

final int DELAY_TIME = 50000;final int RADIUS = 20;int x, y, direction, colorVal;Color clr = Color.blue;

public void drawBall (Graphics g, int x, int y, int radius , Color clr){

g.setColor (clr);g.fillOval (x – radius, y – radius , 2 * radius, 2 * radius);g.setColor (Color.black);g.drawOval (x – radius, y – radius, 2 * radius, 2 * radius);

} // drawBall method

public void paint (Graphics g){

int appletWidth = getSize ().width;int appletHeight = getSize ().height;// Draw the pattern ten times.for (int loopCtr = 0 ; loopCtr < 10 ; loopCtr++){

while ((RADIUS <= x) && (x <= appletWidth – RADIUS) &&(RADIUS <= y) && (y <= appletHeight – RADIUS))

{drawBall (g, x, y, RADIUS, clr);direction = (int) (Math.random () * 4);if (direction == 0)

y –= 10;else if (direction == 1)

x += 10;else if (direction == 2)

y += 10;else

x –= 10;// Pause to allow the pattern to be viewed.delay (DELAY_TIME);

}

Page 96: 6916388 Problems and Solutions in Java

Page 94

// Start the ball in the center of the applet.x = appletWidth / 2;y = appletHeight / 2;// Use fillRect to erase the background.g.setColor (Color.white);g.fillRect (0, 0, appletWidth, appletHeight);// Generate a number between 0 and 2 to determine the colour// of the next ball to be drawn.colorVal = (int) (Math.random () * 3);if (colorVal == 0)

clr = Color.green;else if (colorVal == 1)

clr = Color.red;else

clr = Color.blue;}

} // paint method

public void delay (int howLong){

// This wastes time.for (int i = 1 ; i <= howLong ; i++){

double garbage = Math.PI * Math.PI;}

} // delay method} // C1110 class

Page 97: 6916388 Problems and Solutions in Java

Page 95

Exercise #11

Write an applet to control the type font with check boxes to indicate bold or italic, radiobuttons to choose the type style, radio buttons to choose the point size, and a text field tocontain the text whose font is to be controlled.

Solution

// Chapter #11 - Exercise #11 (C1111.java)// Note: This applet should be run in at least a 300x350 window. You can// change the window size after the initial run using "Run with Args".

import java.applet.Applet;import java.awt.*;

public class C1111 extends Applet{

private TextField name;private Checkbox boldFont, italicFont, sansSerif, serif, monoSpaced;private Checkbox p16, p20, p24;private CheckboxGroup style, fontSize;private Font f;private Panel pStyle, pFont, pFontStyle, pText;String fontName;

public void init (){

name = new TextField ("Sample Text", 24);// Create the style checkboxes.boldFont = new Checkbox ("Bold");italicFont = new Checkbox ("Italic");// Set the initial state of the text field.f = new Font ("SansSerif", Font.PLAIN, 16);// Set the font type.name.setFont (f);// Set up a group of Checkboxes for font style.style = new CheckboxGroup ();// Check SansSerif radio button only to start.sansSerif = new Checkbox ("SansSerif", style, true);serif = new Checkbox ("Serif", style, false );monoSpaced = new Checkbox ("Monospaced", style, false );// Set up a CheckBox group for font size.fontSize = new CheckboxGroup ();p16 = new Checkbox ("16 pt.", fontSize, true);p20 = new Checkbox ("20 pt.", fontSize, false );p24 = new Checkbox ("24 pt.", fontSize, false );// Create the panels to group the various objects.pFont = new Panel ();pStyle = new Panel ();pText = new Panel ();pFontStyle = new Panel ();// Add each object to the appropriate panel.pText.add (name);

Page 98: 6916388 Problems and Solutions in Java

Page 96

pStyle.add (boldFont);pStyle.add (italicFont);pFontStyle.add (sansSerif);pFontStyle.add (serif);pFontStyle.add (monoSpaced);pFont.add (p16);pFont.add (p20);pFont.add (p24);setLayout (new GridLayout (4, 1, 2, 2));// Add the panels to the applet.add (pText);add (pStyle);add (pFontStyle);add (pFont);

} // init method

public boolean action (Event e, Object o){

int box1, box2, fontPoint;if (e.target instanceof Checkbox){

// Read the state of Bold box.if (boldFont.getState () == true)

box1 = Font.BOLD;else

box1 = Font.PLAIN;// Read the state of Italic box.if (italicFont.getState () == true)

box2 = Font.ITALIC;else

box2 = Font.PLAIN;// Read the state of the font style Checkboxes.if (sansSerif.getState () == true)

fontName = "SansSerif";else if (serif.getState () == true)

fontName = "Serif";else

fontName = "Monospaced";// Check the state of the font size Checkboxes.if (p16.getState () == true)

fontPoint = 16;else if (p20.getState () == true)

fontPoint = 20;else

fontPoint = 24;// Set the font to display any changes.f = new Font (fontName, box1 + box2, fontPoint);name.setFont (f);

}return true;

} // action method} // C1111 class

Page 99: 6916388 Problems and Solutions in Java

Page 97

Chapter 12.12 Solutions

Exercise #1

Create the HTML to produce a web page that is similar to the title page of this chapter.

Solution

C1201.html

<html><head>

<title>Chapter 12 - Question 1</title></head>

<body><font size="+3">Chapter 12</font>

<br><br><center><font size="+4">Creating Web Pages<br> with HTML</font><br><br><br><br><table width="100%"><tr> <td width="25%">&nbsp;</td> <td width="75%"><a href="C1202.html#121">12.1 The Hypertext MarkupLanguage</a>&nbsp;&nbsp;<br><hr size="4" width="100%" noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%"><a href="C1202.html#122">12.2 Markup Tags</a>&nbsp;<br><hrsize="4" width="100%" noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.3 HTML Documents&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.4 HTML Tags for Formatting Text&nbsp;&nbsp;<br><hr size="4"width="100%" noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.5 Linked Web Pages&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.6 Tables in Web Pages&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td>

Page 100: 6916388 Problems and Solutions in Java

Page 98

</tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.7 Images in Web Pages&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.8 Applets in Web Pages&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.9 An Example Web Page with Applets&nbsp;&nbsp;<br><hr size="4"width="100%" noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.10 Chapter Summary&nbsp;&nbsp;<br><hr size="4" width="100%"noshade></td></tr><tr> <td width="25%">&nbsp;</td> <td width="75%">12.11 Exercises&nbsp;&nbsp;<br></td></tr>

</table>

</body></html>

Page 101: 6916388 Problems and Solutions in Java

Page 99

Exercise #2

Create the HTML to produce a web page that is similar to the first summary page of thischapter. Arrange that the title page of Exercise 1 have links to the first two entries of thesummary page for the first two sections of the Chapter: 12.1 and 12.2.

Solution

C1202.html

<html><head>

<title>Chapter 12 Question 2</title></head>

<body>Chapter 12 : Creating Web Pages with HTML<br><hr size="4" width="100%" noshade><font size="+2">12.10 Chapter Summary</font><br><br><table width="100%"><tr > <td width="7%">&nbsp;</td> <td width="93%">&nbsp;&nbsp;&nbsp;&nbsp;Java and the Internet are closely connected.Java applets can beshared over the Internet and can be incorporated into web pages toprovide attention-getting animated components. This chapterdiscussed how web pages can be created and how applets can beincluded in them.</td></tr></table><br>

<font size="+1"><a name="121"></a>Hypertext Markup Language (HTML)</font><br><br><table width="100%"><tr > <td width="7%">&nbsp;</td> <td width="93%">Since web pages must be able to be downloaded to a variety ofcomputer platforms, the text of the pages must be marked withtags to describe how the text is to be displayed, for example: whena new paragraph is to begin; what is to be a heading; and so on. Aweb page is often more than one of a series of pages that can beexamined linearly. It is usually a <b>hypertext</b> that allows the readerto move from one point in the text, the <b>link</b>, to another point, quiteoften on a different page, called the <b>destination</b>. In this waypersons scanning the page can find out more information about aparticular item that interests them. <b>Tags</b> must be incorporated inthe marked up web page to permit this hypertext property.<br></td></table><br>

Page 102: 6916388 Problems and Solutions in Java

Page 100

<font size="+1"><a name="122"></a>Markup Tags</font><br><br><table width="100%"><tr > <td width="7%">&nbsp;</td> <td width="93%">&nbsp;&nbsp;&nbsp;&nbsp;Markup tags must be distinctive from the textthat willultimately appear on the web page. To accomplish this, all tags areenclosed in angle brackets. Each tag type has a name. For example,a tag for a major heading has the tag name H1. For a less importantheading, a sub-heading, the tag name might be H2.Many tags come in pairs that bracket the text controlled by thetag. The end tag has the same tag name as the beginning tag exceptthat it has a slash (/) in front of the name. The form for bracketedtag pairs is<br><br>&nbsp;&nbsp;&nbsp;&lt;tag-name&gt;web text &nbsp;&lt;/tag-name&gt;<br><br>The actual appearance of a web page element on a computer screen can varyfrom one computer platform to another, but the meaning is preserved.For example, a heading might appear in bold face on one computer platformand underlined on a different one.</tr></table>

</body></html>

Page 103: 6916388 Problems and Solutions in Java

Page 101

Exercise #3

Change the web page for “Frank’s Used Cars” so that the bouncing sign is “Drive aWreck” and is in cyan-colored letters.

Solution

Change the HTML parameters to the BouncingText applet as follows

<APPLET CODE="BouncingText.class" WIDTH=500 HEIGHT=100> <PARAM NAME="message" VALUE="Drive a Wreck!"> <PARAM NAME="color" VALUE="cyan"> <PARAM NAME="bgcolor" VALUE="yellow"></APPLET>

Page 104: 6916388 Problems and Solutions in Java

Page 102

Exercise #4

Change the HTML of the applet to provide the color in which the scrolling text is to bedisplayed and change the applet code to get the value of the color parameter.

Solution

// Chapter #12 - Exercise #4 (C1204)

import java.applet.*;import java.awt.*;

public class C1204 extends Applet{

String message = "Scrolling Example"; // The scrolled default message.static final int SIZE = 40; // The font size of the message.static final int SPEED = 5; // The speed that it is scrolled.Color textColor = Color.black; // The default text color.

// Read parameter "message" from HTML.public void init (){

// Get the message from a parameter, if available.if (getParameter ("message") != null ){

message = getParameter ("message");}

// Read the "color" parameter.if (getParameter ("color") != null ){

String textColorString = getParameter ("color");if (textColorString.equalsIgnoreCase ("red"))

textColor = Color.red;else if (textColorString.equalsIgnoreCase ("green"))

textColor = Color.green;else if (textColorString.equalsIgnoreCase ("blue"))

textColor = Color.blue;else if (textColorString.equalsIgnoreCase ("yellow"))

textColor = Color.yellow;else if (textColorString.equalsIgnoreCase ("cyan"))

textColor = Color.cyan;else if (textColorString.equalsIgnoreCase ("white"))

textColor = Color.white;else if (textColorString.equalsIgnoreCase ("black"))

textColor = Color.black;}

Page 105: 6916388 Problems and Solutions in Java

Page 103

// Read the "bgcolor" parameter.if (getParameter ("bgcolor") != null ){

String textColorString = getParameter ("bgcolor");if (textColorString.equalsIgnoreCase ("red"))

setBackground (Color.red);else if (textColorString.equalsIgnoreCase ("green"))

setBackground (Color.green);else if (textColorString.equalsIgnoreCase ("blue"))

setBackground (Color.blue);else if (textColorString.equalsIgnoreCase ("yellow"))

setBackground (Color.yellow);else if (textColorString.equalsIgnoreCase ("cyan"))

setBackground (Color.cyan);else if (textColorString.equalsIgnoreCase ("white"))

setBackground (Color.white);else if (textColorString.equalsIgnoreCase ("black"))

setBackground (Color.black);}

} // init method

public void start (){

Font font = new Font ("Serif", Font.BOLD, SIZE);Graphics g = getGraphics ();int fontHeight = getFontMetrics (font).getAscent ();int appletWidth = size ().width;int appletHeight = size ().height;int x = 0;// Set the y location of the text so that the message// is centered vertically.int y = (appletHeight + fontHeight) / 2;

show ();g.setFont (font);

while (true){

// Draw the message twice in order to get the impression// of scrolling off the left edge.g.setColor (textColor);g.drawString (message, x, y);g.drawString (message, x – appletWidth, y);

// Pause 40 milliseconds.try{

Thread.sleep (40);}catch (InterruptedException e){}

Page 106: 6916388 Problems and Solutions in Java

Page 104

// Erase the message in the previous location.g.setColor (getBackground ());g.drawString (message, x, y);g.drawString (message, x – appletWidth, y);

// Change the location, scrolling it to the left. When the// location moves off the left edge, move it to the right edge.x –= SPEED;if (x < 0)

x = appletWidth;}

} // start method} // C1204 class

Change the HTML parameters to the ScrollingText applet as follows

<APPLET CODE="ScrollingText.class" WIDTH=500 HEIGHT=100><PARAM NAME="message" VALUE="Frank's Used Cars!"><PARAM NAME="color" VALUE="red"><PARAM NAME="bgcolor" VALUE="green">

</APPLET>

Page 107: 6916388 Problems and Solutions in Java

Page 105

Chapter 13.10 Solutions

Exercise #1

Modify the Normalize program that generates the random numbers so that the largestvalue is found in the same loop that generates the list of random values.

Solution

// Chapter #13 - Exercise #1 (C1301.java)

import java.awt.*;import hsa.Console;

public class C1301{

static Console c;

static public void main (String args []){

c = new Console ();// Normalize each element in a list of 10 random integers,// dividing it by the largest integer in the list.final int SIZE = 9;int list [] = new int [SIZE + 1];// Generate random value for list.int largest = 0;for (int i = 0 ; i <= SIZE ; i++){

list [i] = (int ) (Math.random () * 1000) + 1;// Find largest value in the list.if (list [i] > largest)

largest = list [i];}// Output normalized values.for (int i = 0 ; i <= SIZE ; i++){

c.print (i, 3);c.println ((double ) list [i] / largest, 7, 2);

}} // main method

} // C1301 class

Page 108: 6916388 Problems and Solutions in Java

Page 106

Exercise #2

The program to find primes can be improved in several ways. One improvement resultsfrom using an array to store a boolean value only for the odd integers (since every eveninteger larger than 2 is not prime) and to treat 2 as a special case. This means that the itharray entry corresponds to the integer 2i+1. A program that incorporates thisimprovement could look for primes over twice as large a range with a given amount ofmemory. Modify the program to store a boolean value only for odd integers.

Solution

// Chapter #13 - Exercise #2 (C1302.java)

import java.awt.*;import hsa.Console;

public class C1302{

static Console c;

static public void main (String args []){

c = new Console ();

// Find prime numbers using Erastosthenes' sieve.int size;c.print ("Enter maximum value to test: ");size = c.readInt ();// Round down to an odd number.if (size % 2 == 0)

size––;// Declare array isPrime.boolean isPrime [];isPrime = new boolean [(size – 1) / 2 + 1];// A boolean array is automatically initialized to false.// Initialize array elements as true.for (int i = 0 ; i < isPrime.length ; i++){

isPrime [i] = true;}// Multiples of a prime are not prime.for (int i = 3 ; i <= size ; i += 2){

if (isPrime [(i – 1) / 2]) // This value is prime.{

for (int j = 2 * i ; j <= size ; j += i){

// Do not use even values of j as they are no// longer in the array.if (j % 2 == 1)

isPrime [(j – 1) / 2] = false ;

Page 109: 6916388 Problems and Solutions in Java

Page 107

}}

}c.println ("Between 2 and " + size + " the primes are:");final int valuesPerLine = 10;int valuesPrinted = 0;for (int i = 0 ; i < isPrime.length ; i++){

if (isPrime [i]){

if (i == 0)c.print (2, 5);

elsec.print (2 * i + 1, 5);

valuesPrinted++;if (valuesPrinted % valuesPerLine == 0)

c.println ("");}

}if ((valuesPrinted % valuesPerLine) != 0)

c.println ("");} // main method

} // C1302 class

Page 110: 6916388 Problems and Solutions in Java

Page 108

Exercise #3

Make the prime number program more efficient by combining the iteration that marksvalues with the iteration that prints unmarked values.

Solution

// Chapter #13 - Exercise #3 (C1303.java)// This version moves the marking and printing into one// iteration of the array.

import java.awt.*;import hsa.Console;

public class C1303{

static Console c;

static public void main (String args []){

c = new Console ();// Find prime numbers using Erastosthenes' sieve.int size;c.print ("Enter maximum value to test: ");size = c.readInt ();if (size % 2 == 0)

size––;// Declare array isPrime.boolean isPrime [];isPrime = new boolean [(size – 1) / 2 + 1];// A boolean array is automatically initialized to false.// Initialize array elements as true.for (int i = 0 ; i < isPrime.length ; i++){

isPrime [i] = true;}// Set up values for print control.c.println ("Between 2 and " + size + " the primes are:");final int valuesPerLine = 10;int valuesPrinted = 1;// Print out "2", the special prime.c.print (2, 5);// Multiples of a prime are not prime.for (int i = 3 ; i <= size ; i += 2){

if (isPrime [(i – 1) / 2]) // This value is prime.{

if (i == 0)c.print (2, 5);

elsec.print (i, 5);

valuesPrinted++;

Page 111: 6916388 Problems and Solutions in Java

Page 109

if (valuesPrinted % valuesPerLine == 0)c.println ("");

for (int j = 2 * i ; j <= size ; j += i){

// Do not use even values of j as they are no// longer in the array.if (j % 2 == 1)

isPrime [(j – 1) / 2] = false ;}

}}if ((valuesPrinted % valuesPerLine) != 0)

c.println ("");} // main method

} // C1303 class

Page 112: 6916388 Problems and Solutions in Java

Page 110

Exercise #4

Write a program that reads a list of names from a file and outputs the list with anyduplicates removed.

Solution

// Chapter #13 - Exercise #4 (C1304.java)import java.awt.*;import java.io.*;import java.util.*;import hsa.Console;

public class C1304{

static Console c;

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

c = new Console ();String inputName;String infileName, outfileName;String names [];names = new String [25];int numNames = 0;boolean nameFound;// Get file name and output line length from the user.int maxLength, outLength ;c.print ("Enter the name of the input file: ");infileName = c.readLine ();BufferedReader input;// Open the output file.input = new BufferedReader (new FileReader (infileName));// Get the name of the output file and open it.c.print ("Enter the name of the output file: ");outfileName = c.readLine ();PrintWriter output;output = new PrintWriter (new FileWriter (outfileName));// Read the first name directly into the array.names [0] = input.readLine ();numNames = 1;// Read the second name.inputName = input.readLine ();// Loop until the input file is empty.while (inputName != null ){

nameFound = false ;// Use boolean nameFound to mark whether a name is a// duplicate that is already in the array.for (int ctr = 0 ; ctr < numNames ; ctr++){

if (inputName.equals (names [ctr]))

Page 113: 6916388 Problems and Solutions in Java

Page 111

nameFound = true;}// If the name is not found, add it to the array.if (!nameFound){

numNames++;names [numNames – 1] = inputName;

}inputName = input.readLine ();

}// Output the names to file.for (int ctr = 0 ; ctr < numNames ; ctr++){

output.println (names [ctr]);// Print names to screen for visual check.c.println (names [ctr]);

}// Close the output file.output.close ();

} // main method} // C1304 class

Page 114: 6916388 Problems and Solutions in Java

Page 112

Exercise #5

Write a program to read an unordered list of integers. The list is to be printed inascending order. Keep an associated list that marks those values that have been printed.The program should use an iteration to find the smallest unmarked value, print it, andmark it.

Solution

// Chapter #13 - Exercise #5 (C1305.java)

import java.awt.*;import java.io.*;import java.util.*;import hsa.Console;

public class C1305{

static Console c;

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

c = new Console ();String infileName, inputNumber;int numbersCtr = 0, large, small, smallPtr = 0;int numbers [];boolean numbersPrint [];BufferedReader input;numbers = new int [25];numbersPrint = new boolean [25];while (true){

try{

// Get file name from the user.c.print ("Enter the name of the input file: ");infileName = c.readLine ();// Open the input file.input = new BufferedReader (new FileReader (infileName));break ;

}catch (IOException ioe){

c.println ("File not found, please try again...");}

}// Read the first number from the file.inputNumber = input.readLine ();large = Integer.parseInt (inputNumber);// Loop until the input file has been read.while (inputNumber != null )

Page 115: 6916388 Problems and Solutions in Java

Page 113

{numbers [numbersCtr] = Integer.parseInt (inputNumber);// Find largest value to help find smaller values later.if (numbers [numbersCtr] > large)

large = numbers [numbersCtr];numbersPrint [numbersCtr] = false ;numbersCtr++;inputNumber = input.readLine ();

}c.println ();c.println ("The numbers in ascending order...");// Perform n squared iterations. The outer loop processes and// prints one number in each iteration.for (int outer = 0 ; outer < numbersCtr ; outer++){

small = large;// Inner loop to find the smallest number not yet printed.for (int inner = 0 ; inner < numbersCtr ; inner++){

if (numbers [inner ] < small && !numbersPrint [inner ]){

// Must mark both the value (small) and// location(smallPtr).small = numbers [inner ];smallPtr = inner ;

}}c.println (Integer.toString (small));numbersPrint [smallPtr] = true;

}} // main method

} // C1305 class

Page 116: 6916388 Problems and Solutions in Java

Page 114

Exercise #6Extend the class definition for BookList to include a method called printAuthors that printsthe list with each author being listed once, and all of the books by that author indentedunder the author's name.

Solution

// Chapter #13 - Exercise #6 (C1306.java)

import java.awt.*;import hsa.Console;

public class C1306{

static Console c;

static public void main (String args []){

c = new Console ();// Instantiate an object of BookListPrint class.BookListPrint books = new BookListPrint (c);while (true){

c.println ("Commands you can give after the prompt >");c.println ("i insert a book into the list");c.println ("d delete a book from the list");c.println ("a print the list by author");c.println ("p print the list of books");c.println ("q quit");char command;c.print ("> "); // Prompt for command.command = c.readLine ().charAt (0);if (command == 'q')

break ;switch (command){

case 'i':String newAuthor, newTitle;c.print ("Enter author to insert: ");newAuthor = c.readLine ();c.print ("Enter title to insert: ");newTitle = c.readLine ();books.insert (newAuthor, newTitle);break ;

case 'd':String oldAuthor, oldTitle;c.print ("Enter author to delete: ");oldAuthor = c.readLine ();c.print ("Enter title to delete: ");oldTitle = c.readLine ();books.delete (oldAuthor, oldTitle);break ;

case 'p':

Page 117: 6916388 Problems and Solutions in Java

Page 115

books.printList ();break ;

case 'a':books.printAuthors ();break ;

}}

} // main method} // C1306 class

BookListPrint.java

// The "BookListPrint" class.// A class to maintain a list of authors and titles.

import hsa.Console;

public class BookListPrint extends BookList{

boolean authorPrint [] = new boolean [MAX];String authorName;

// Constructorpublic BookListPrint (Console c){

super (c);} // BookList constructor

public void printAuthors (){

for (int ctr = 0 ; ctr < size ; ctr++){

authorPrint [ctr] = false ;}for (int outer = 0 ; outer < size ; outer++){

authorName = author [outer];if (!authorPrint [outer]){

c.println (author [outer]);c.println (" " + title [outer]);authorPrint [outer] = true;for (int inner = outer + 1 ; inner < size ; inner++){

if (author [inner ].equals (author [outer])){

c.println (" " + title [inner]);authorPrint [inner] = true;

}}

}}

} // printAuthors method} // BookListPrint class

Page 118: 6916388 Problems and Solutions in Java

Page 116

Exercise #7

A two-dimensional array of characters can be used to store a picture if the blank is usedfor background and an asterisk is used for non-blank parts. Write a class for pictures thathas two methods. The first method should put a horizontal line into the picture; themethod will have the coordinates of the endpoints as parameters. The second method willoutput a picture.

Solution

// Chapter #13 - Exercise #7 (C1307.java)

import java.awt.*;import hsa.Console;

public class C1307{

static Console c;

static public void main (String args []){

c = new Console ();int x1, x2, y;

// A main method to test the class TextPicture.// Instantiate an object of TextPicture class.TextPicture tp = new TextPicture (c);while (true){

c.println ("Commands you can give after the prompt >");c.println ("c - clear the current picture");c.println ("h - draw a horizontal line");c.println ("d - display the current picture");c.println ("q - quit");char command;c.print ("> "); // Prompt for command.command = c.readLine ().charAt (0);if (command == 'q'){

c.println ("The program has ended");break ;

}switch (command){

case 'c':tp.clear ();c.println ("The picture has been cleared");break ;

case 'h':c.print ("Enter the left column value where " +

"the line begins (0-79): ");x1 = c.readInt ();

Page 119: 6916388 Problems and Solutions in Java

Page 117

c.print ("Enter the right column value where " +"the line ends (0-79): ");

x2 = c.readInt ();c.print ("Enter the row value of the line (0-24): ");y = c.readInt ();tp.drawHorizontal (x1, y, x2);c.println ("The line has been added");break ;

case 'd':tp.display ();break ;

} // switch} // while (true)

} // main method} // C1307 class

TextPicture.java

// The "TextPicture" class.// A class to draw and display a picture drawn with text authors and titles.

import hsa.Console;

public class TextPicture{

// Declare variables.char pictureMap [] [] = new char [25] [80];Console c;

// Constructorpublic TextPicture (Console c){

this.c = c;clear ();

} // TextPicture constructor

// Clear the picture.public void clear (){

for (int row = 1 ; row < 25 ; row++){

for (int col = 0 ; col < 80 ; col++){

pictureMap [row] [col] = ' ';}

}} // clear method

Page 120: 6916388 Problems and Solutions in Java

Page 118

// Draw a horizontal line.public void drawHorizontal (int x1, int row, int x2){

for (int col = x1 ; col <= x2 ; col++){

pictureMap [row] [col] = '*';}

} // drawHorizontal method

// Display the picture.public void display (){

for (int row = 1 ; row < 25 ; row++){

for (int col = 0 ; col < 80 ; col++){

c.print (pictureMap [row] [col]);}c.println ();

}} // display method

} // TextPicture class

Page 121: 6916388 Problems and Solutions in Java

Page 119

Exercise #8

Extend the class from the previous exercise to allow a rectangle to be inserted into apicture.

Solution

// Chapter #13 - Exercise #8 (C1308.java)

import java.awt.*;import hsa.Console;

public class C1308{

static Console c;

static public void main (String args []){

c = new Console ();int x1, x2, y, y1, y2;

// Create a TextPictureRect object which inherits from TextPicture.TextPictureRect tpr = new TextPictureRect (c);c.println ("Commands you can give after the prompt >");c.println ("c - clear the current picture");c.println ("h - draw a horizontal line");c.println ("r - draw a rectangle");c.println ("d - display the current picture");c.println ("q - quit");while (true){

char command;c.print ("> "); // Prompt for command.command = c.readLine ().charAt (0);if (command == 'q'){

c.println ("The program has ended");break ;

}switch (command){

case 'c': // Clear the screen.tpr.clear ();c.println ("The picture has been cleared");break ;

case 'h': // Draw a horizontal line.c.print ("Enter the left column value where " +

"the line begins (0-79): ");x1 = c.readInt ();c.print ("Enter the right column value where " +

"the line ends (0-79): ");x2 = c.readInt ();

Page 122: 6916388 Problems and Solutions in Java

Page 120

c.print ("Enter the row value of the line: ");y = c.readInt ();tpr.drawHorizontal (x1, y, x2);c.println ("The line has been added");break ;

case 'r': // Draw a rectangle.c.print ("Enter the upper left column value: ");x1 = c.readInt ();c.print ("Enter the upper left row value: ");y1 = c.readInt ();c.print ("Enter the lower right column value: ");x2 = c.readInt ();c.print ("Enter the lower right row value: ");y2 = c.readInt ();tpr.drawRectangle (x1, y1, x2, y2);c.println ("The rectangle has been added");break ;

case 'd': // Display the current picture.tpr.display ();break ;

} // switch} // while (true)

} // main method} // C1308 class

TextPictureRect.java

// The "TextPictureRect" class.// A class to extend TextPicture.

import hsa.Console;

public class TextPictureRect extends TextPicture{

// Constructorpublic TextPictureRect (Console c){

super (c);} // TextPictureRect constructor

// Clear the picture.public void drawRectangle (int x1, int y1, int x2, int y2){

for (int row = y1 ; row <= y2 ; row++){

for (int col = x1 ; col < x2 ; col++){

pictureMap [row] [col] = '*';}

}} // drawRectangle method

} // TextPictureRect class

Page 123: 6916388 Problems and Solutions in Java

Page 121

Exercise #9

Extend the class from the previous exercise to allow a circle to be inserted into a picture.

Solution

// Chapter #13 - Exercise #9 (C1309.java)

import java.awt.*;import hsa.Console;

public class C1309{

static Console c;

static public void main (String args []){

c = new Console ();int x1, x2, y, y1, y2, r;// Create a TextPictureRect object which inherits from TextPicture.TextPictureCircle tpc = new TextPictureCircle (c);while (true){

c.println ("Commands you can give after the prompt >");c.println ("e - erase the current picture");c.println ("h - draw a horizontal line");c.println ("r - draw a rectangle");c.println ("c - insert a circle");c.println ("d - display the current picture");c.println ("q - quit");char command;c.print ("> "); // Prompt for command.command = c.readLine ().charAt (0);if (command == 'q'){

c.println ("The program has ended");break ;

}switch (command){

case 'e': // Clear the screen.tpc.clear ();c.println ("The picture has been cleared");break ;

case 'h': // Draw a horizontal line.c.print ("Enter the left column value where " +

"the line begins (0-79): ");x1 = c.readInt ();c.print ("Enter the right column value where " +

"the line ends (0-79): ");x2 = c.readInt ();c.print ("Enter the row value of the line: ");y = c.readInt ();

Page 124: 6916388 Problems and Solutions in Java

Page 122

tpr.drawHorizontal (x1, y, x2);c.println ("The line has been added");break ;

case 'r': // Draw a rectangle.c.print ("Enter the upper left column value: ");x1 = c.readInt ();c.print ("Enter the upper left row value: ");y1 = c.readInt ();c.print ("Enter the lower right column value: ");x2 = c.readInt ();c.print ("Enter the lower right row value: ");y2 = c.readInt ();tpr.drawRectangle (x1, y1, x2, y2);c.println ("The rectangle has been added");break ;

case 'c': // Draw a circle.c.print ("Enter the column of the center: ");x1 = c.readInt ();c.print ("Enter the row of the center: ");y1 = c.readInt ();c.print ("Enter the radius: ");r = c.readInt ();tpc.drawCircle (y1, x1, r);c.println ("The circle has been added");break ;

case 'd': // Display the current picture.tpc.display ();break ;

} // switch} // while (true)

} // main method} // C1309 class

TextPictureCircle.java

// The "TextPictureCircle" class.// A class to extend TextPicture to allow insertion of a circle// into the drawing area.

import hsa.Console;

public class TextPictureCircle extends TextPictureRect{

// Constructorpublic TextPictureCircle (Console c){

super (c);} // TextPictureCircle constructor

// Clear the picture.public void drawCircle (int centerRow, int centerCol, int radius){

Page 125: 6916388 Problems and Solutions in Java

Page 123

double extRadius = (double) radius + .4;int x;for (int ctr = 0 ; ctr <= radius ; ctr++){

x = (int) Math.round (Math.sqrt (extRadius * extRadius –ctr * ctr));

drawHorizontal (centerCol – x, centerRow + ctr, centerCol + x);drawHorizontal (centerCol – x, centerRow – ctr, centerCol + x);

}} // drawCircle method

} // TextPictureCircle class

Page 126: 6916388 Problems and Solutions in Java

Page 124

Chapter 14.10 Solutions

Exercise #1

The Shape hierarchy could have been designed with no abstract class Shape. Instead, theancestor class could have been Oval with Triangle and Rectangle inheriting from Oval andoverriding the draw and the erase methods. Discuss the advantages and disadvantages ofthis hierarchy.

Solution

There is some minor benefit to using Oval as the ancestor class to the Shapehierarchy. It reduces in the number of classes needed to implement the hierarchy,thus making the hierarchy slighly easier to understand.

However, this advantage is strongly outweighed by the fact that the logical structureof the class hierarchy is lost by using Oval as the ancestor class. A Rectangle is not atype of Oval, as would be implied by Rectangle inheriting from Oval. Such confusionmakes it much more difficult for future programmers to decide where to place newclasses in the hierarchy.

More confusing still, all classes in the hierarchy would include the xRadius andyRadius field, which would be inapplicable for the vast majority of new classes.

Finally, with draw and erase already defined, if a programmer forgot to override themethods, they would get an incorrect implementation of the two methods (mostclasses probably wouldn't use the Oval's draw and erase methods) instead of an errorduring compilation indicating the the abstract methods hadn't been overridden. Asalways, a program bug is much harder and costlier to correct than a compilationerrors.

Default implementations for methods are usually only a good thing if most, if not all,of the subclasses will use them. Otherwise, making the method abstract is preferable.

Page 127: 6916388 Problems and Solutions in Java

Page 125

Exercise #2Design a class hierarchy (specifying data and public methods) for a library automationsystem that includes books, periodicals, audio tapes, and software. Each type of itemshould contain information particular to the item (that is ISSN for periodicals). Thesystem should have the means to enter items into the collection, remove items from thecollection, check items in and out and inquire into the status of an item.

Solution

A full library automation system can be found in Appendix A. Questions 2-5 willbuild a much simplified system. Note the solution below is only one possiblesolution. Many solutions may suggest themselves and be equally valid.

The main hierarchy would be an Item, which is an item in the library. An Itemwould be an abstract class in the same fashion as Shape was in chapter 14.Descending from Item are the actual different types of items: Book, Periodical,AudioTape and Software.

Here is a possible implementation of Item.

Item:

Fields:

String titleString dueDate

Methods:

getTitle ()checkOutItem (int libraryCardNumber,

String dueDate)checkInItem ()getStatus ()

The four subclasses would each have their own constructor and override thegetStatus method. They would all have some extra fields (minimized here forclarity).

Book: String author String isbnPeriodical: String issueDate String issnAudioTape: String artistSoftware: String hardwareRequirement

The main program should be able to:

1) Add an item to the collection 2) Remove an item from the collection 3) Check an item out (the user gives the library card #|

and due date) 4) Check an item back in 5) List the status of all the items

The library's collection of items could be implemented either as an array or a linkedlist.

Page 128: 6916388 Problems and Solutions in Java

Page 126

Exercise #3

Implement the class hierarchy in Exercise 2. Test your design by creating a new class forvideo tapes in the collection.

Solution

This is, by the way, an excellent way of testing an O-O design. Once the design iscompleted, ask students to extend their design. If that can be done with minimaleffort, then the original design was good.

Note that these solutions use the hsa.Stdin and hsa.Stdout classes to do simple inputand output. One could also equally successfully use the hsa.Console class. SeeAppendix D pgs 691-694 of "Introduction to Programming in Java" fordocumentation of the two classes.

Item.java

// The "Item" class.

import hsa.*;

public abstract class Item{

static final int CHECKED_IN = –1;

String title;int card; // The card that checked the book out.String dueDate; // The date the book is due back.

public Item (){

card = CHECKED_IN;} // Item constructor

// We use this method for formatting. It returns a string containing// the number of spaces specified.String justify (String s, int fieldSize){

StringBuffer answer = new StringBuffer (s);

for (int cnt = 0 ; cnt < fieldSize – s.length () ; cnt++){

answer.append (" ");}

return answer.toString ();} // spaces

Page 129: 6916388 Problems and Solutions in Java

Page 127

// Return a String containing the title in a left-justified field of length 20.String getTitleStatus (){

if (card != CHECKED_IN){

return justify (title, 20) + " " +justify ("(Out to " + card + ")", 14) + " ";

}else{

return justify (title, 35) + " ";}

} // getTitleStatus

public String getTitle (){

return title;} // getTitle method

// Checks out an item and returns the status message.public String checkOutItem (int card, String dueDate){

if (this.card != CHECKED_IN){

return "Can't check out " + title +"! It is currently checked out to card number " +this.card + " and is due back " + this.dueDate;

}else{

this.card = card;this.dueDate = dueDate;return title + " is now checked out";

}} // checkOutItem method

public String checkInItem (){

if (card != CHECKED_IN){

int oldCard = card;card = CHECKED_IN;return title + " checked in. (It was checked out to card #" +

oldCard + " and due back " + dueDate + ")";}else{

return "Can't check in " + title + "! It is not checked out.";}

} // checkInItem method

public abstract String getStatus ();} // Item class

Page 130: 6916388 Problems and Solutions in Java

Page 128

Book.java

// The "Book" class.

import hsa.*;

public class Book extends Item{

String isbn;

public Book (){

Stdout.print ("Book title: ");title = Stdin.readLine ();Stdout.print ("ISBN: ");isbn = Stdin.readLine ();

} // Book constructor

public Book (String title, String isbn){

this.title = title;this.isbn = isbn;

} // Book constructor

public String getStatus (){

return getTitleStatus () + isbn;} // getStatus method

} // Book class

Periodical.java

// The "Periodical" class.

import hsa.*;

public class Periodical extends Item{

String issn;String issueDate;

public Periodical (String title, String issueDate, String issn){

this.title = title;this.issueDate = issueDate;this.issn = issn;

} // Periodical constructor

Page 131: 6916388 Problems and Solutions in Java

Page 129

public Periodical (){

Stdout.print ("Periodical title: ");title = Stdin.readLine ();Stdout.print ("Issue Date: ");issueDate = Stdin.readLine ();Stdout.print ("ISSN: ");issn = Stdin.readLine ();

} // Periodical constructor

public String getStatus (){

return getTitleStatus () + justify (issn, 13) + " " + issueDate;} // getStatus

} // Periodical class

AudioTape.java

// The "AudioTape" class.

import hsa.*;

public class AudioTape extends Item{

String artist;

public AudioTape (){

Stdout.print ("Audio tape title: ");title = Stdin.readLine ();Stdout.print ("Artist: ");artist = Stdin.readLine ();

} // AudioTape constructor

public AudioTape (String title, String artist){

this.title = title;this.artist = artist;

} // AudioTape constructor

public String getStatus (){

return getTitleStatus () + artist;} // getStatus method

} // AudioTape class

Page 132: 6916388 Problems and Solutions in Java

Page 130

Software.java

// The "Software" class.

import hsa.*;

public class Software extends Item{

String hardwareRequirements;

public Software (){

Stdout.print ("Software title: ");title = Stdin.readLine ();Stdout.print ("Hardware requirements: ");hardwareRequirements = Stdin.readLine ();

} // Software constructor

public Software (String title, String hardwareRequirements){

this.title = title;this.hardwareRequirements = hardwareRequirements;

} // Software constructor

public String getStatus (){

return getTitleStatus () + hardwareRequirements;} // getStatus method

} // Software class

Page 133: 6916388 Problems and Solutions in Java

Page 131

Exercise #4

Create a text-only main program to run the library automation system. Create a new setof classes for library card holders and provide some way of adding and removing cardholders.

Solution

// The "C1404" class.import hsa.*;

public class C1404{

static int MAX_ITEMS = 100;static int NOT_FOUND = –1;

static Item [] collection;static int numItems = 0;

static int findItem (String title){

for (int cnt = 0 ; cnt < numItems ; cnt++){

if (title.equals (collection [cnt].getTitle ())){

return cnt;}

}return NOT_FOUND;

} // findItem

static void addItem (){

int itemType;Item item;

if (numItems == MAX_ITEMS){

Stdout.println ("Can't fit any more items into the collection");return;

}Stdout.println ("What type of item would you like to add? ");Stdout.println (" (1) Book");Stdout.println (" (2) Periodical");Stdout.println (" (3) Audio Tape");Stdout.println (" (4) Software");Stdout.println ();Stdout.print ("Choice: ");itemType = Stdin.readInt ();

Page 134: 6916388 Problems and Solutions in Java

Page 132

if (itemType == 1)item = new Book ();

else if (itemType == 2)item = new Periodical ();

else if (itemType == 3)item = new AudioTape ();

else if (itemType == 4)item = new Software ();

else{

Stdout.println ("Unrecognized choice");return;

}

collection [numItems] = item;numItems++;

} // addItem method

static void removeItem (){

String title;int location;

Stdout.print ("What is the title of the item to be removed? ");title = Stdin.readLine ();

location = findItem (title);

if (location == NOT_FOUND){

Stdout.println ("'" + title + "' not found in the collection.");}else{

// Remove the item from the array. Note the item object// itself and any objects it uses will be garbage collected// when there are no more references to it.for (int cnt1 = location + 1 ; cnt1 < numItems ; cnt1++){

collection [cnt1 – 1] = collection [cnt1];}

// If we don't make the last entry in the collection null,// there will be a pointer to it even if we aren't using it// and it will never be garbage collected.collection [numItems – 1] = null ;numItems––;

}} // removeItem method

Page 135: 6916388 Problems and Solutions in Java

Page 133

static void checkOutItem (){

String title, statusMessage;int location;

Stdout.print ("What is the title of the item to be checked out? ");title = Stdin.readLine ();

location = findItem (title);

if (location == NOT_FOUND){

Stdout.println ("'" + title + "' not found in the collection.");}else{

Item item = collection [location];int card;String dueDate;

Stdout.print ("Enter the library card #: ");card = Stdin.readInt ();Stdout.print ("Enter the due date: ");dueDate = Stdin.readLine ();

statusMessage = item.checkOutItem (card, dueDate);Stdout.println (statusMessage);

}} // checkOutItem method

static void checkInItem (){

String title, statusMessage;int location;

Stdout.print ("What is the title of the item to be checked in? ");title = Stdin.readLine ();

location = findItem (title);

if (location == NOT_FOUND){

Stdout.println ("'" + title + "' not found in the collection.");}else{

Item item = collection [location];statusMessage = item.checkInItem ();Stdout.println (statusMessage);

}} // checkInItem method

Page 136: 6916388 Problems and Solutions in Java

Page 134

static void listItems (){

for (int cnt = 0 ; cnt < numItems ; cnt++){

Item item = collection [cnt];Stdout.println (item.getStatus ());

}} // listItems method

public static void main (String [] args){

int choice;

collection = new Item [MAX_ITEMS];

Stdout.println ("Library Automation System");Stdout.println ("-------------------------");while (true){

Stdout.println ();Stdout.println ("(1) Add an item to the collection");Stdout.println ("(2) Remove an item from the collection");Stdout.println ("(3) Check an item out");Stdout.println ("(4) Check an item back in");Stdout.println ("(5) List the status of all the items");Stdout.println ("(6) Quit");Stdout.println ();Stdout.print ("Choice: ");choice = Stdin.readInt ();

if (choice == 1)addItem ();

else if (choice == 2)removeItem ();

else if (choice == 3)checkOutItem ();

else if (choice == 4)checkInItem ();

else if (choice == 5)listItems ();

else if (choice == 6)break ;

}} // main method

} // C1404 class

Page 137: 6916388 Problems and Solutions in Java

Page 135

Exercise #5

Create a GUI application or applet front end to the library automation system.

Solution

This is an extremely difficult exercise and is probably better used as an end ofsemester project. The program uses the Item, Book, Periodical, AudioTape andSoftware classes.

The program divides the applet window into five parts using a three parts using aBorderLayout. The top and bottom of the window are Labels used for instruction andstatus messages.

The rest of the window is divided into three panels. The left panel(commandButtonPanel ) contains the command buttons. The middle panel(itemKindPanel) contains the buttons to specify what type of item to add. The rightpanel (commandCompletionPanel) contains whatever components are needed tocomplete the currently executing command. The set of components in that panelchange each time a command is executed.

In order to make certain that the user doesn't press an incorrect button, the applethides any panels that aren't applicable at the moment.

When a command is to be completed, the applet removes all the components fromthe right panel commandCompletionPanel and places the components are necessaryfor the given command. It then displays the components. Note that after adding thecomponents to the panel, it is necessary for the panel to call validate. The validatemethod lays out all the components in the panel.

In the applet's init method, the program lays out all the components in the first twopanels and a set of components in the third panel and makes all three panels visiblebefore calling validate for the applet. The validate method allocates space in thewindow for each of the three panels. If the third panel was left empty when validatewas called, the applet would (incorrectly) assume that no space was required for thethird panel. The init method then hides the middle and right panel.

In most cases, the components added consist of one or more text fields along withlabels and a button. The user is to enter the data in the text fields and press thebutton. Pressing any button in the applet causes the action method to be called.When the button in the commandCompletionPanel is pressed, the action methodcalls another method to make certain that the fields were filled in. Once it has theappropriate data from the user, the program then processes the commands in thesame manner as Exercise #4.

The user interface could be made much prettier with additional effort.

From this example, you can understand why two thirds of the code in a modernmicrocomputer program may pertain to the user interface!

Page 138: 6916388 Problems and Solutions in Java

Page 136

// The "C1405" class.

import java.applet.*;import java.awt.*;

public class C1405 extends Applet{

static int MAX_ITEMS = 100;static int NOT_FOUND = –1;

static Item [] collection;static int numItems = 0;

// Buttons for commands.Button addItemButton, removeItemButton, checkOutItemButton;Button checkInItemButton, listItemsButton, quitButton;// Buttons indicating type of item to add.Button addBookButton, addPeriodicalButton, addAudioTapeButton;Button addSoftwareButton;// Text labels and fields for adding item to collection.Label bookGetTitleLabel, bookGetISBNLabel;TextField bookGetTitle, bookGetISBN;Label periodicalGetTitleLabel, periodicalGetIssueDateLabel;Label periodicalGetISSNLabel;TextField periodicalGetTitle, periodicalGetIssueDate;TextField periodicalGetISSN;Label audioTapeGetTitleLabel, audioTapeGetArtistLabel;TextField audioTapeGetTitle, audioTapeGetArtist;Label softwareGetTitleLabel, softwareGetHardwareRequirementsLabel;TextField softwareGetTitle, softwareGetHardwareRequirements;// Buttons for adding an item to collection.Button addBookCompleteButton, addPeriodicalCompleteButton;Button addAudioTapeCompleteButton, addSoftwareCompleteButton;// Text labels, text fields and buttons for removing an item from// collection.Label removeItemTitleLabel;TextField removeItemTitle;Button removeItemCompleteButton;// Text labels, text fields and buttons for checking out an item.Label checkOutItemTitleLabel, checkOutDueDateLabel;Label checkOutCardNumLabel;TextField checkOutItemTitle, checkOutDueDate, checkOutCardNum;Button checkOutItemCompleteButton;// Text labels, text fields and buttons for checking in an item.Label checkInItemTitleLabel;TextField checkInItemTitle;Button checkInItemCompleteButton;// Text label, text area and button for listing items.Label listOfItemsLabel;TextArea listOfItems;Button listItemsCompleteButton;

Page 139: 6916388 Problems and Solutions in Java

Page 137

// Label to place status messages in.Label instructionMessage, statusMessage;// Panels in which components are to be placed.Panel commandButtonPanel, itemKindPanel, commandCompletionPanel;

static int findItem (String title){

for (int cnt = 0 ; cnt < numItems ; cnt++){

if (title.equals (collection [cnt].getTitle ())){

return cnt;}

}return NOT_FOUND;

} // findItem

public void init (){

// Create the collection of library items.collection = new Item [MAX_ITEMS];

// Note, adding a GUI to a program can triple its length!

// Lay out the GUI components.

// The applet itself will use a border layout. The instructions// are at the top ("North"), the status message is at the bottom// ("South"), the main command buttons are on the left ("West"),// the different items to add are in the middle ("Center") and// the text fields for all the commands are on the right ("East").setLayout (new BorderLayout ());

// Create the instruction message at the top of the window.instructionMessage = new Label ("Click a Command Button",

Label.CENTER);instructionMessage.setForeground (Color.red);add ("North", instructionMessage);

// Create the instruction message at the top of the window.statusMessage = new Label ("", Label.CENTER);statusMessage.setForeground (Color.magenta);add ("South", statusMessage);

// Lay out all the command buttons.addItemButton = new Button ("Add Item to Collection");removeItemButton = new Button ("Remove Item from Collection");checkOutItemButton = new Button ("Check Out Item");checkInItemButton = new Button ("Check In Item");listItemsButton = new Button ("List Items in Collection");quitButton = new Button ("Quit");commandButtonPanel = new Panel (new GridLayout (6, 1));commandButtonPanel.add (addItemButton);

Page 140: 6916388 Problems and Solutions in Java

Page 138

commandButtonPanel.add (removeItemButton);commandButtonPanel.add (checkOutItemButton);commandButtonPanel.add (checkInItemButton);commandButtonPanel.add (listItemsButton);commandButtonPanel.add (quitButton);add ("West", commandButtonPanel);

// Lay out the item types.addBookButton = new Button ("Add Book");addPeriodicalButton = new Button ("Add Periodical");addAudioTapeButton = new Button ("Add Audio Tape");addSoftwareButton = new Button ("Add Software");itemKindPanel = new Panel (new GridLayout (6, 1));itemKindPanel.add (addBookButton);itemKindPanel.add (addPeriodicalButton);itemKindPanel.add (addAudioTapeButton);itemKindPanel.add (addSoftwareButton);add ("Center", itemKindPanel);

// Lay out some of the command completion components.periodicalGetTitleLabel = new Label ("Periodical Title");periodicalGetTitle = new TextField ();periodicalGetISSNLabel = new Label ("ISSN Number");periodicalGetISSN = new TextField ();periodicalGetIssueDateLabel = new Label ("Issue Date");periodicalGetIssueDate = new TextField ();addPeriodicalCompleteButton =

new Button ("Add Periodical to Collection");commandCompletionPanel = new Panel (new GridLayout (7, 1));commandCompletionPanel.add (periodicalGetTitleLabel);commandCompletionPanel.add (periodicalGetTitle);commandCompletionPanel.add (periodicalGetIssueDateLabel);commandCompletionPanel.add (periodicalGetIssueDate);commandCompletionPanel.add (periodicalGetISSNLabel);commandCompletionPanel.add (periodicalGetISSN);commandCompletionPanel.add (addPeriodicalCompleteButton);add ("East", commandCompletionPanel);

// Create the rest of the components needed for books.bookGetTitleLabel = new Label ("Book Title");bookGetTitle = new TextField ();bookGetISBNLabel = new Label ("ISBN Number");bookGetISBN = new TextField ();addBookCompleteButton = new Button ("Add Book to Collection");// Create the rest of the components needed for audio tapes.audioTapeGetTitleLabel = new Label ("Audio Tape Title");audioTapeGetTitle = new TextField ();audioTapeGetArtistLabel = new Label ("Artist");audioTapeGetArtist = new TextField ();addAudioTapeCompleteButton =

new Button ("Add Audio Tape to Collection");

Page 141: 6916388 Problems and Solutions in Java

Page 139

// Create the rest of the components needed for software.softwareGetTitleLabel = new Label ("Software Title");softwareGetTitle = new TextField ();softwareGetHardwareRequirementsLabel =

new Label ("Hardware Requirements");softwareGetHardwareRequirements = new TextField ();addSoftwareCompleteButton =

new Button ("Add Software to Collection");// Create the rest of the components needed for removing an item.removeItemTitleLabel = new Label ("Title to be removed");removeItemTitle = new TextField ("");removeItemCompleteButton =

new Button ("Remove Item from Collection");// Create the rest of the components needed for checking out an item.checkOutItemTitleLabel = new Label ("Title to be checked out");checkOutItemTitle = new TextField ("");checkOutDueDateLabel = new Label ("Due Date");checkOutDueDate = new TextField ("");checkOutCardNumLabel = new Label ("Library Card Number");checkOutCardNum = new TextField ("");checkOutItemCompleteButton = new Button ("Check Out Item");// Create the rest of the components needed for checking in an item.checkInItemTitleLabel = new Label ("Title to be checked in");checkInItemTitle = new TextField ("");checkInItemCompleteButton = new Button ("Check In Item");// Create the rest of the components needed for listing items.listOfItemsLabel = new Label ("Items in the Collection");listOfItems = new TextArea (10, 20);listItemsCompleteButton = new Button ("Finish Viewing List");

// This causes the current components to be laid out in the applet.validate ();

itemKindPanel.hide ();commandCompletionPanel.hide ();

} // init method

// Add Item to the Collectionpublic void addItemCommand (){

// If the array is full, display a status messageif (numItems == MAX_ITEMS){

statusMessage.setText ("Cannot add any more items to collection");return;

}

// Hide the command panel and show the panel containing the// buttons with the type of items to add.commandButtonPanel.hide ();itemKindPanel.show ();

Page 142: 6916388 Problems and Solutions in Java

Page 140

// Set the instructions.instructionMessage.setText ("Click Type of Item to Add");statusMessage.setText ("");

} // addItemCommand method

// Remove Item from the Collection.public void removeItemCommand (){

// Remove any previous text from the text fields.removeItemTitle.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (removeItemTitleLabel);commandCompletionPanel.add (removeItemTitle);commandCompletionPanel.add (removeItemCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title of Item to Be Removed");statusMessage.setText ("");

} // removeItem method

void removeItemCompletedCommand (){

String title;int location;

// Make certain the user entered a title and an ISBN.title = removeItemTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title " +"and Click Button");

statusMessage.setText ("Title field must not be blank");return;

}

location = findItem (title);

if (location == NOT_FOUND){

statusMessage.setText ("'" + title + "' not found in the collection.");}else{

Page 143: 6916388 Problems and Solutions in Java

Page 141

// Remove the item from the array. Note the item object// itself and any objects it uses will be garbage collected// when there are no more references to it.for (int cnt1 = location + 1 ; cnt1 < numItems ; cnt1++){

collection [cnt1 – 1] = collection [cnt1];}

// If we don't make the last entry in the collection null,// there will be a pointer to it even if we aren't using it// and it will never be garbage collected.collection [numItems – 1] = null ;numItems––;statusMessage.setText (title + " removed from the collection.");

}

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

// Set the instructions.instructionMessage.setText ("Click a Command Button");

} // removeItemCompletedCommand method

// Check Out Item from the Collection.public void checkOutItemCommand (){

// Remove any previous text from the text fieldscheckOutItemTitle.setText ("");checkOutDueDate.setText ("");checkOutCardNum.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (checkOutItemTitleLabel);commandCompletionPanel.add (checkOutItemTitle);commandCompletionPanel.add (checkOutDueDateLabel);commandCompletionPanel.add (checkOutDueDate);commandCompletionPanel.add (checkOutCardNumLabel);commandCompletionPanel.add (checkOutCardNum);commandCompletionPanel.add (checkOutItemCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title, Due Date and Library " +

"Card # and Click Button");statusMessage.setText ("");

} // checkOutItemCommand method

Page 144: 6916388 Problems and Solutions in Java

Page 142

void checkOutItemCompleteCommand (){

String title, dueDate, cardNumberString;int cardNumber;Item item;int location;

// Make certain the user entered a title and an ISBN.title = checkOutItemTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}dueDate = checkOutDueDate.getText ();if (dueDate.length () == 0){

instructionMessage.setText ("You Must Enter a Due Date and " +"Click Button");

statusMessage.setText ("Due date field must not be blank");return;

}cardNumberString = checkOutCardNum.getText ();if (cardNumberString.length () == 0){

instructionMessage.setText ("You Must Enter a Card Number " +" and Click Button");

statusMessage.setText ("Card number field must not be blank");return;

}try{

cardNumber = Integer.parseInt (cardNumberString);}catch (NumberFormatException e){

instructionMessage.setText ("You Must Enter a Numeric Card " +"Number and Click Button");

statusMessage.setText ("Card number field must contain " +"an integer");

return;}

location = findItem (title);

if (location == NOT_FOUND){

statusMessage.setText ("'" + title + "' not found in the collection.");}else{

Page 145: 6916388 Problems and Solutions in Java

Page 143

item = collection [location];

statusMessage.setText (item.checkOutItem (cardNumber, dueDate));}

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

// Set the instructions.instructionMessage.setText ("Click a Command Button");

} // checkOutItemCompleteCommand method

// Check In Item to the Collection.public void checkInItemCommand (){

// Remove any previous text from the text fields.checkInItemTitle.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (checkInItemTitleLabel);commandCompletionPanel.add (checkInItemTitle);commandCompletionPanel.add (checkInItemCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title and Click Button");statusMessage.setText ("");

} // checkInItemCommand method

public void checkInItemCompleteCommand (){

String title;Item item;int location;

// Make certain the user entered a title and an ISBN.title = checkInItemTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}

Page 146: 6916388 Problems and Solutions in Java

Page 144

location = findItem (title);

if (location == NOT_FOUND){

statusMessage.setText ("'" + title + "' not found in the collection.");}else{

item = collection [location];statusMessage.setText (item.checkInItem ());

}} // checkInItemCompleteCommand method

// List Items in the Collection.public void listItemsCommand (){

// Remove any previous text from the text area.listOfItems.setText ("");

// Add the listing of all the items.for (int cnt = 0 ; cnt < numItems ; cnt++){

Item item = collection [cnt];listOfItems.append (item.getStatus ());listOfItems.append ("\n");

}

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (listOfItemsLabel);commandCompletionPanel.add (listOfItems);commandCompletionPanel.add (listItemsCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Click Button to Return to " +

"Command Buttons");statusMessage.setText ("");

} // listItemsCommand method

public void listItemsCompleteCommand (){

// Hide the command completion panel and make the command// buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

Page 147: 6916388 Problems and Solutions in Java

Page 145

// Set the instructions.instructionMessage.setText ("Click a Command Button");

} // listItemsCompleteCommand method

// Add Book to the Collection.public void addBookCommand (){

// Remove any previous text from the text fields.bookGetTitle.setText ("");bookGetISBN.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (bookGetTitleLabel);commandCompletionPanel.add (bookGetTitle);commandCompletionPanel.add (bookGetISBNLabel);commandCompletionPanel.add (bookGetISBN);commandCompletionPanel.add (addBookCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter title and ISBN and " +

"Click Button");statusMessage.setText ("");

} // addBookCommand method

public void addBookCompletedCommand (){

String title, isbn;Item item;

// Make certain the user entered a title and an ISBN.title = bookGetTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}isbn = bookGetISBN.getText ();if (isbn.length () == 0){

instructionMessage.setText ("You Must Enter an ISBN and " +"Click Button");

statusMessage.setText ("ISBN field must not be blank");return;

}

Page 148: 6916388 Problems and Solutions in Java

Page 146

// Create the new book.item = new Book (title, isbn);

collection [numItems] = item;numItems++;

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

// Set the instructions.instructionMessage.setText ("Click a Command Button");statusMessage.setText ("Book Added to Collection");

} // addBookCompletedCommand method

// Add Periodical to the Collection.public void addPeriodicalCommand (){

// Remove any previous text from the text fieldsperiodicalGetTitle.setText ("");periodicalGetIssueDate.setText ("");periodicalGetISSN.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (periodicalGetTitleLabel);commandCompletionPanel.add (periodicalGetTitle);commandCompletionPanel.add (periodicalGetIssueDateLabel);commandCompletionPanel.add (periodicalGetIssueDate);commandCompletionPanel.add (periodicalGetISSNLabel);commandCompletionPanel.add (periodicalGetISSN);commandCompletionPanel.add (addPeriodicalCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title, Issue Date and ISSN " +

"and Click Button");statusMessage.setText ("");

} // addPeriodicalCommand method

public void addPeriodicalCompletedCommand (){

String title, issn, issueDate;Item item;

Page 149: 6916388 Problems and Solutions in Java

Page 147

// Make certain the user entered a title and an ISBN.title = periodicalGetTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}issueDate = periodicalGetIssueDate.getText ();if (issueDate.length () == 0){

instructionMessage.setText ("You Must Enter an Issue Date " +"and Click Button");

statusMessage.setText ("Issue date field must not be blank");return;

}issn = periodicalGetISSN.getText ();if (issn.length () == 0){

instructionMessage.setText ("You Must Enter an ISSN and " +"Click Button");

statusMessage.setText ("ISSN field must not be blank");return;

}

// Create the new periodical.item = new Periodical (title, issn, issueDate);

collection [numItems] = item;numItems++;

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

// Set the instructions.instructionMessage.setText ("Click a Command Button");statusMessage.setText ("Periodical Added to Collection");

} // addPeriodicalCompletedCommand method

// Add Audio Tape to the Collection.public void addAudioTapeCommand (){

// Remove any previous text from the text fields.audioTapeGetTitle.setText ("");audioTapeGetArtist.setText ("");

Page 150: 6916388 Problems and Solutions in Java

Page 148

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (audioTapeGetTitleLabel);commandCompletionPanel.add (audioTapeGetTitle);commandCompletionPanel.add (audioTapeGetArtistLabel);commandCompletionPanel.add (audioTapeGetArtist);commandCompletionPanel.add (addAudioTapeCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title and Artist and " +

"Click Button");statusMessage.setText ("");

} // addAudioTapeCommand method

public void addAudioTapeCompletedCommand (){

String title, artist;Item item;

// Make certain the user entered a title and an ISBN.title = audioTapeGetTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}artist = audioTapeGetArtist.getText ();if (artist.length () == 0){

instructionMessage.setText ("You Must Enter an Artist and " +"Click Button");

statusMessage.setText ("Artist field must not be blank");return;

}

// Create the new audioTape.item = new AudioTape (title, artist);

collection [numItems] = item;numItems++;

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

Page 151: 6916388 Problems and Solutions in Java

Page 149

// Set the instructions.instructionMessage.setText ("Click a Command Button");statusMessage.setText ("Audio Tape Added to Collection");

} // addAudioTapeCompletedCommand method

// Add Software to the Collection.public void addSoftwareCommand (){

// Remove any previous text from the text fields.softwareGetTitle.setText ("");softwareGetHardwareRequirements.setText ("");

// Hide the panel containing the buttons with the type of items// to add. Add the appropriate components to the command// completion panel and make it show.itemKindPanel.hide ();commandCompletionPanel.removeAll ();commandCompletionPanel.add (softwareGetTitleLabel);commandCompletionPanel.add (softwareGetTitle);commandCompletionPanel.add (softwareGetHardwareRequirementsLabel);commandCompletionPanel.add (softwareGetHardwareRequirements);commandCompletionPanel.add (addSoftwareCompleteButton);commandCompletionPanel.validate ();commandCompletionPanel.show ();

// Set the instructions.instructionMessage.setText ("Enter Title and Hardware " +

"Requirements and Click Button");statusMessage.setText ("");

} // addSoftwareCommand method

public void addSoftwareCompletedCommand (){

String title, hardwareRequirements;Item item;

// Make certain the user entered a title and an ISBN.title = softwareGetTitle.getText ();if (title.length () == 0){

instructionMessage.setText ("You Must Enter a Title and " +"Click Button");

statusMessage.setText ("Title field must not be blank");return;

}hardwareRequirements = softwareGetHardwareRequirements.getText ();if (hardwareRequirements.length () == 0){

instructionMessage.setText ("You Must Enter the Hardware " +"Requirements and Click Button");

statusMessage.setText ("Hardware requirements field must " +"not be blank");

Page 152: 6916388 Problems and Solutions in Java

Page 150

return;}

// Create the new software.item = new Software (title, hardwareRequirements);

collection [numItems] = item;numItems++;

// Hide the command completion panel and make the// command buttons show.commandCompletionPanel.hide ();commandButtonPanel.show ();

// Set the instructions.instructionMessage.setText ("Click a Command Button");statusMessage.setText ("Software Added to Collection");

} // addSoftwareCompletedCommand method

// This method is called whenever a button is pressed.public boolean action (Event e, Object o){

// Main command buttonsif (e.target == addItemButton){

addItemCommand ();return true;

}else if (e.target == removeItemButton){

removeItemCommand ();return true;

}else if (e.target == checkOutItemButton){

checkOutItemCommand ();return true;

}else if (e.target == checkInItemButton){

checkInItemCommand ();return true;

}else if (e.target == listItemsButton){

listItemsCommand ();return true;

}else if (e.target == quitButton){

Page 153: 6916388 Problems and Solutions in Java

Page 151

commandButtonPanel.hide ();itemKindPanel.hide ();commandCompletionPanel.hide ();instructionMessage.setText ("");statusMessage.setText ("Program Terminated");

}

// Which item to add buttons.else if (e.target == addBookButton){

addBookCommand ();return true;

}else if (e.target == addPeriodicalButton){

addPeriodicalCommand ();return true;

}else if (e.target == addAudioTapeButton){

addAudioTapeCommand ();return true;

}else if (e.target == addSoftwareButton){

addSoftwareCommand ();return true;

}

// Completing adding an item.else if (e.target == addBookCompleteButton){

addBookCompletedCommand ();return true;

}else if (e.target == addPeriodicalCompleteButton){

addPeriodicalCompletedCommand ();return true;

}else if (e.target == addAudioTapeCompleteButton){

addAudioTapeCompletedCommand ();return true;

}else if (e.target == addSoftwareCompleteButton){

addSoftwareCompletedCommand ();return true;

}

Page 154: 6916388 Problems and Solutions in Java

Page 152

// Complete removing an item.else if (e.target == removeItemCompleteButton){

removeItemCompletedCommand ();return true;

}// Complete checking out an item.else if (e.target == checkOutItemCompleteButton){

checkOutItemCompleteCommand ();return true;

}// Complete checking in an item.else if (e.target == checkInItemCompleteButton){

checkInItemCompleteCommand ();return true;

}// Complete listing items.else if (e.target == listItemsCompleteButton){

listItemsCompleteCommand ();return true;

}

return false ;} // action method

} // C1405 class

Page 155: 6916388 Problems and Solutions in Java

Page 153

Exercise #6

The slide method of Shape bounces objects whenever x or y go over an edge. This meansthat for objects like the Oval, the object bounces when the center of the oval hits an edge.Modify the necessary class or classes so that the shapes bounce whenever they touch anedge. Is there a way of doing this without having to have multiple implementations of theslide method?

Solution

The Shape class is modified by adding some extra fields that hold the boundaries ofthe shape.

protected int x1, y1, x2, y2; // The boundaries of the shape

The move methods are modified to change x1, y1 and x2, y2 as x and y are changed.

// Move the shape to a new location.public void move (int x, int y){

// Move the objects boundaries.x1 += x – this.x;y1 += y – this.y;x2 += x – this.x;y2 += y – this.y;

if (visible){

erase ();this.x = x;this.y = y;draw ();

}else{

this.x = x;this.y = y;

}} // move method

// If the user does not specify the coordinates to move to, then// move the shape to a new random location.public void move (){

int newX = (int) (Math.random () * surfaceWidth);int newY = (int) (Math.random () * surfaceHeight);

// Move the objects boundaries.x1 += newX – this.x;y1 += newY – this.y;x2 += newX – this.x;y2 += newY – this.y;

Page 156: 6916388 Problems and Solutions in Java

Page 154

if (visible){

erase ();this.x = newX;this.y = newY;draw ();

}else{

this.x = newX;this.y = newY;

}} // move method

// Slide the shape in the direction specified by dx, dy. If the shape// has slid off the edge of the drawing surface, reverse the direction// of that motion increment.public void slide (){

if ((x1 < 0) || (x2 >= surfaceWidth))dx = –dx;

if ((y1 < 0) || (y2 >= surfaceHeight))dy = –dy;

move (x + dx, y + dy);} // slide method

Finally the slide method is modified

// Slide the shape in the direction specified by dx, dy. If the shape// has slid off the edge of the drawing surface, reverse the direction// of that motion increment.public void slide (){

if ((x1 < 0) || (x2 >= surfaceWidth))dx = –dx;

if ((y1 < 0) || (y2 >= surfaceHeight))dy = –dy;

move (x + dx, y + dy);} // slide method

For each kind of shape, when the shape's location is specified, the boundaries of theshape must also be set.

For Oval, each constructor has the following lines added

x1 = x – xRadius; y1 = y – yRadius; x2 = x + xRadius; y2 = y + yRadius;

Page 157: 6916388 Problems and Solutions in Java

Page 155

For Rectangle, each constructor has the following lines added

x1 = x; y1 = y; x2 = x + rectWidth; y2 = y + rectHeight;

The inheriting classes use the same constructors. However, a modification of theconstructor is required for the rabbit, in order to make the ears bounce of the wall. Ineach of the Rabbit constructors, the following two lines are added

// The ears make the rabbit a different shape from an Oval y1 = y – 2 * xRadius;

These two lines are executed after the ancestor's constructor is called, so x1, x2 andy2 are already correctly set.

Page 158: 6916388 Problems and Solutions in Java

Page 156

Exercise #7

If you obscure the ShapeTest applet window by dragging another window over top of it,you will occasionally see part of a shape left behind. Explain how this can occur. Modifythe Shape class to minimize this occurring. Can it be eliminated entirely?

Solution

Answering this question requires some knowledge about how Java works.

When an Applet window is obscured by another window and then revealed when thetopmost window is moved, the Java system automatically calls the paint method ofthe Applet. This occurs simultaneously with the execution of the start method ofapplet.

This means that the paint method might be called while a shape was in the middle ofexecuting its move method. If we look at the move method, for a visible shape, we seeit has

if (visible){

erase ();this.x = x;this.y = y;draw ();

}

If we look at the paint method, it has

// Redraw the shape if it is visible.public void paint (){

if (visible){

draw ();}

} // paint method

If we examine these for a while, we can see what occasionally happens.

Here is a concrete example. We are moving a shape from (100, 50) to (102, 50). Theprogram executes the move method of the shape. It first calls the erase method forthe shape. This means that the figure at (100, 50) is no longer on the screen. Theuser moves a window that was overtop of the Applet window at exactly this point.The paint method is called by the Java system to redraw the part of the Appletwindow that was exposed. The visible variable is true, so the paint method redrawsthe shape (at (100, 50)) that we just erased and then returns.

Page 159: 6916388 Problems and Solutions in Java

Page 157

Execution of the move method continues with the x being changed to 102. The figureis then redrawn at (102,50), almost completely over the figure at (100, 50). When wenext move the shape, the image at (102, 50) is erased, but this leaves a tiny slice of thefigure that was drawn by the paint method at (100,50). The figure moves away, andthe tiny piece of the image remains on the screen until another shape passes over it.

To avoid this problem, we can change a portion of the move method so that theshape cannot be redrawn by the paint method while we are performing the move.Here is a modified version of this section of the method.

if (visible){

visible = false;erase ();this.x = x;this.y = y;draw ();visible = true;

}

This exercise gives you a little taste of some of the challenges of concurrency,something that will be faced by anyone writing Java programs performinganimation.

Page 160: 6916388 Problems and Solutions in Java

Page 158

Chapter 15.8 Solutions

Exercise #1

A StudentRecords class is to be defined with these instance variable definitions.

String name; // Allow 40 characters.int mark [] = new int [4];double average;

Create an array of 26 such records and initialize them with simulated data giving namesA, B, C, D and so on to the students. Fill in marks for each record as random numbersbetween 0 and 100. Give all the averages a temporary value of −1. Store the array as a filein binary form.

Solution

// Chapter #15 - Exercise #1 (C1501.java)

import java.awt.*;import java.io.*;import hsa.Console;

public class C1501{

static Console c;

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

c = new Console ();// Instantiate the array.StudentRecords sr [] = new StudentRecords [26];// Instantiate the file object.RandomAccessFile marksFile =

new RandomAccessFile ("marks", "rw");int nameNum = 65;int marks [] = new int [4];String name;double average;Character cName;// Generate the sample data and then use it to create objects.for (int recCtr = 0 ; recCtr < 26 ; recCtr++){

// Each name will one upper case letter A,B,C,...// Each "name" is generated from ASCII code, the integer value// is converted to character and then String.cName = new Character ((char) (nameNum + recCtr));name = cName.toString ();for (int markCtr = 0 ; markCtr < 4 ; markCtr++){

marks [markCtr] = (int ) (Math.random () * 101);}

Page 161: 6916388 Problems and Solutions in Java

Page 159

average = –1;sr [recCtr] = new StudentRecords (name, marks, average);

}// Write each record in the array to file.for (int recCtr = 0 ; recCtr < 26 ; recCtr++){

marksFile.seek ((long) recCtr * sr [recCtr].recordSize ());sr [recCtr].write (marksFile);

}c.println ("The records have been created and written to file");

} // main method} // C1501 class

Page 162: 6916388 Problems and Solutions in Java

Page 160

Exercise #2

Read the binary file created in Exercise 1, computing the average mark for the student andrecording it in average. Read each record, process it, and return it as an updated record tothe binary file.

At the same time compute the class average for each of the four subjects and the overallaverage mark outputting them in a summary.

Solution

// Chapter #15 - Exercise #2 (C1502.java) marks file

import java.awt.*;import java.io.*;import hsa.Console;

public class C1502{

static Console c;

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

c = new Console ();// Instantiate the file object.RandomAccessFile marksFile =

new RandomAccessFile ("marks", "rw");// Variables to match one record of StudentRecords.String name;int marks [] = new int [4];double average;// StudentRecords object and record size.StudentRecords student ;final int RSIZE = 108;// Variables for summary data.double sumAverage;int sumMarks [] = new int [4];for (int ctr = 0 ; ctr < 4 ; ctr++){

sumMarks [ctr] = 0;}sumAverage = 0;// Generate the sample data and then use it to create objects.for (int recCtr = 0 ; recCtr < 26 ; recCtr++){

marksFile.seek ((long) recCtr * RSIZE);student = new StudentRecords (marksFile);student.getMarks (marks);for (int ctr = 0 ; ctr < 4 ; ctr++){

sumMarks [ctr] += marks [ctr];}

Page 163: 6916388 Problems and Solutions in Java

Page 161

student.calcAverage ();sumAverage += student.getAverage ();marksFile.seek ((long) recCtr * RSIZE);student.write (marksFile);

}c.println ("Mark 1 Average = " + (double ) (sumMarks [0] / 26.0));c.println ("Mark 2 Average = " + (double ) (sumMarks [1] / 26.0));c.println ("Mark 3 Average = " + (double ) (sumMarks [2] / 26.0));c.println ("Mark 4 Average = " + (double ) (sumMarks [3] / 26.0));c.println ();c.println ("Overall Average = " + (double ) (sumAverage / 26.0));

} // main method} // C1502 class

Page 164: 6916388 Problems and Solutions in Java

Page 162

Exercise #3

Devise a program so that individual students could request information from the file withthe proper averages. Be sure to have a directory created.

Solution

// Chapter #15 - Exercise #3 (C1503.java) marks file

import java.io.*;import hsa.Console;

public class C1503{

static int recordNumber = 26;static String directory [] = new String [26];static final int RSIZE = 108;static StudentRecords student ;

public static int find (String name){

int count = 0;int location = –1;while (count < recordNumber && location == –1){

if (name.compareTo (directory [count]) == 0)location = count;

elsecount++;

}return location;

} // find method

// Main method to find name in directory.public static void main (String args []) throws IOException{

Console c = new Console ();String choice;String name;int marks [] = new int [4];double average;// Open school file to read and write.RandomAccessFile marksFile =

new RandomAccessFile ("marks", "rw");for (int recCtr = 0 ; recCtr < 26 ; recCtr++){

marksFile.seek ((long) recCtr * RSIZE);student = new StudentRecords (marksFile);directory [recCtr] = student.getName ();if (recCtr < 10)

c.println ("The student name is " + student.getName ());

Page 165: 6916388 Problems and Solutions in Java

Page 163

}StudentRecords student ;while (true){

c.println ("Enter");c.println (" f to find student information");c.println (" q to quit");c.print ("Choice: ");choice = c.readLine ();if (choice.equals ("f")){

c.print ("Enter the name of the student: ");name = c.readLine ();int location = find (name);if (location == –1){

c.println (name + " not found");}else{

marksFile.seek ((long) location *StudentRecords.recordSize ());

student = new StudentRecords (marksFile);c.println ("Name = " + name);c.println ("Average = " + student.getAverage ());

}}else if (choice.equals ("q")){

break ;}

}} // main method

} // C1503 class

Page 166: 6916388 Problems and Solutions in Java

Page 164

Exercise #4

Modify the find method used in the Students class of this chapter to use the binarymethod of search on the file created in Exercise 2. This is possible since the records will besorted by name, that is, A first, B second, and so on.

Solution

// Chapter #15 - Exercise #4 (C1504.java)

import java.io.*;import hsa.Console;

public class C1504{

static int recordNumber = 26;static String directory [] = new String [26];static final int RSIZE = 108;static StudentRecords student ;

public static int find (String name){

int first = 0, last = 25;int middle;int where = –1;while (first != last && last > 0){

middle = (first + last) / 2;if (name.compareTo (directory [middle]) <= 0){

last = middle;}else{

first = middle + 1;}where = first;if (where < 26 && name.compareTo (directory [where]) > 0)

where++;}return where;

} // find method

// Main method to find name in directory.public static void main (String args []) throws IOException{

Console c = new Console ();String choice;String name;int marks [] = new int [4];double average;

Page 167: 6916388 Problems and Solutions in Java

Page 165

// Open school file to read and write.RandomAccessFile marksFile =

new RandomAccessFile ("marks", "rw");for (int recCtr = 0 ; recCtr < 26 ; recCtr++){

marksFile.seek ((long) recCtr * RSIZE);student = new StudentRecords (marksFile);directory [recCtr] = student.getName ();if (recCtr < 10)

c.println ("The student name is " + student.getName ());}StudentRecords student ;while (true){

c.println ("Enter");c.println (" f to find student information");c.println (" q to quit");c.print ("Choice: ");choice = c.readLine ();if (choice.equals ("f")){

c.print ("Enter the name of the student: ");name = c.readLine ();int location = find (name);if (location == –1){

c.println (name + " not found");}else{

marksFile.seek ((long) location *StudentRecords.recordSize ());

student = new StudentRecords (marksFile);c.println ("Name = " + name);c.println ("Average = " + student.getAverage ());

}}else if (choice.equals ("q")){

break ;}

}} // main method

} // C1504 class

Page 168: 6916388 Problems and Solutions in Java

Page 166

Exercise #5

In the game of bridge the high-card point value of a hand can be calculated by assigning a4 to an ace, 3 to a king, 2 to a queen, and 1 to a jack. Extend the PlayBridge class so thatthe number of points of each hand is displayed along with the hand itself.

Solution

// Chapter #15 - Exercise #5 (C1505.java)// This is both a class that is instantiated *and* a main program with// a main method. The main method and the console, etc, could be placed// in its own class in order to make things clearer.

import hsa.Console;

public class C1505 extends PlayBridge{

int sumHighPoints [] = new int [5];

public C1505 (){

super ();} // C1505 constructor

public void calculatePoints (){

int tempPoints;// Hands are listed one card to a line unsorted.for (int whichHand = 1 ; whichHand <= NUMBER_OF_HANDS ;

whichHand++){

sumHighPoints [whichHand] = 0;for (int whichCard = 1 ; whichCard <= CARDS_IN_HAND ;

whichCard++){

tempPoints = hand [whichHand] [whichCard].value – 10;if (tempPoints > 0)

sumHighPoints [whichHand] += tempPoints;}

}} // calculatePoints method

// Method for dealing hands from deck (overrides dealHands in// PlayBridge).public void dealHands (){

// Deal one card to each hand in turn repeatedly.int card = 1;for (int cardCount = 1 ; cardCount <= CARDS_IN_HAND ; cardCount++){

Page 169: 6916388 Problems and Solutions in Java

Page 167

for (int handCount = 1 ; handCount <= NUMBER_OF_HANDS ;handCount++)

{hand [handCount] [cardCount] = deck [card];// Move to deal next card.card++;

}}calculatePoints ();

} // dealHands method

// Method for listing hands (overrides listHands in PlayBridge).public void listHands (Console c){

// Hands are listed one card to a line unsorted.for (int whichHand = 1 ; whichHand <= NUMBER_OF_HANDS ;

whichHand++){

c.println ("Here are the cards for hand " + whichHand);for (int whichCard = 1 ; whichCard <= CARDS_IN_HAND ;

whichCard++){

c.print ("" + hand [whichHand] [whichCard].suit + hand[whichHand] [whichCard].value + " ");

}c.println ();c.println ("High card Points " + sumHighPoints [whichHand]);c.println ();

}} // listHands method

// Method to determine if a given pair (1 & 3 or 2 & 4) have a// high point hand of over 25 points.public boolean dealInOneHand (int hand1, int hand2){

if (sumHighPoints [hand1] + sumHighPoints [hand2] > 25)return true;

elsereturn false ;

} // dealInOneHand method

static public void main (String args []){

Console c = new Console ();C1505 deck = new C1505 ();deck.shuffleDeck ();deck.dealHands ();deck.listHands (c);

} // main method} // C1505 class

Page 170: 6916388 Problems and Solutions in Java

Page 168

Exercise #6

In a bridge game players are in pairs that cooperate with each other: player 1 is a partnerof player 3, player 2 is a partner of player 4. If a team has 25 high-card points betweenthem they can score a "game in one hand". Write a program that counts the number oftimes each of the two teams of players could get a game in one hand in a fixed number ofdeals. What is the percentage of the deals that produces a "game in one hand" situation.Try dealing 10 hands to begin, then try dealing 100 hands.

Solution

// Chapter #15 - Exercise #6 (C1506.java)

import hsa.Console;

public class C1506{

static public void main (String args []){

Console c = new Console ();C1505 deck = new C1505 ();int oneHand13 = 0, oneHand24 = 0;int numDeals;double percent13, percent24;c.print ("Enter the number of deals: ");numDeals = c.readInt ();for (int ctr = 1 ; ctr <= numDeals ; ctr++){

deck.shuffleDeck ();deck.dealHands ();if (deck.dealInOneHand (1, 3))

oneHand13++;if (deck.dealInOneHand (2, 4))

oneHand24++;}percent13 = oneHand13 * 100.0 / numDeals;percent24 = oneHand24 * 100.0 / numDeals;c.println ("The number of games in one hand for players 1-3 is " +

oneHand13 + " in Pct. " + percent13 + "%");c.println ("The number of games in one hand for players 2-4 is " +

oneHand24 + " in Pct. " + percent24 + "%");} // main method

} // C1506 class

Page 171: 6916388 Problems and Solutions in Java

Page 169

Chapter 16.10 Solutions

Exercise #1

Write a method that determines the median of a list of n marks. The median is the markthat divides the list (if sorted) into two equal halves. If the list contains an even number ofitems, the halves are different by one item. Use it to find the median of a list of 100simulated exam marks.

Solution

// Chapter #16 - Exercise #1 (C1601.java)

import java.awt.*;import hsa.Console;

public class C1601{

static Console c;static int dataList [];

static public void main (String args []){

// Create Console object.c = new Console ();// median - median position// numItems - number of items in data sampleint median, numItems;c.print ("Enter the number of data items: ");numItems = c.readInt ();dataList = new int [numItems];// Test for odd or even number of data items,// and set median accordingly.if (numItems % 2 == 0)

median = numItems / 2;else

median = numItems / 2 + 1;// Generate numItems of test data.c.println ("Generating a test data set...");dataGen (dataList, numItems);// Show first ten items before the sort.showTen (dataList);c.println ("Sorting the data set");selectionSort (dataList);// Show first ten items after the sort.showTen (dataList);c.println ();c.println ("The median of this list is position " + (median)

+ " in the array.");c.println ("The median data value is " + dataList [median – 1]);

} // main method

Page 172: 6916388 Problems and Solutions in Java

Page 170

// dataGen generates nItem random marks from 1 to 100// and stores the marks in an array.static public void dataGen (int dataList [], int nItems){

for (int ctr = 0 ; ctr < nItems ; ctr++){

dataList [ctr] = (int ) (Math.random () * 100) + 1;}

} // dataGen method

// showTen displays the first 10 records. It is// useful for checking that the sort is working.static public void showTen (int dataList []){

for (int ctr = 0 ; ctr < 10 ; ctr++){

c.println (dataList [ctr]);}

} // showTen method

static public void selectionSort (int data []){

int temp;for (int outer = 0 ; outer < data.length – 1 ; outer++){

for (int inner = outer + 1 ; inner < data.length ; inner++){

if (data [outer] > data [inner ]){

temp = data [outer];data [outer] = data [inner ];data [inner ] = temp;

}} // for

} // for} // selectionSort method

} // C1601 class

Page 173: 6916388 Problems and Solutions in Java

Page 171

Exercise #2

Adapt the insertion sorting method of this chapter to work for a list of student recordswith fields for name, address, and year. The swap and shift methods will also have to bemodified. Test the new sort method.

Solution

// Chapter #16 - Exercise #2 (C1602.java)

import java.awt.*;import java.io.*;import hsa.Console;

public class C1602{

static Console c;static StudentRec sr [];

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

// Create Console and Sorts objects.c = new Console ();StudentRec sr [] = new StudentRec [10];RandomAccessFile stdFile = new RandomAccessFile

("studentdata", "rw");sr [0] = new StudentRec ("Adam", "123 A St.", "2000");sr [1] = new StudentRec ("Michael", "123 A St.", "2001");sr [2] = new StudentRec ("Mary", "218 A St.", "2002");sr [3] = new StudentRec ("Bob", "125 A St.", "1999");sr [4] = new StudentRec ("Pat", "543 A St.", "1998");sr [5] = new StudentRec ("Jessica", "123 A St.", "2000");sr [6] = new StudentRec ("Alex", "193 A St.", "2005");sr [7] = new StudentRec ("Anna", "103 A St.", "2000");sr [8] = new StudentRec ("Paul", "163 A St.", "2003");sr [9] = new StudentRec ("Pat", "777 A St.", "2000");insertionSort (10, sr);for (int ctr = 0 ; ctr < 10 ; ctr++){

c.println (sr [ctr].getName () + " " + sr [ctr].getAddress ()+ " " + sr [ctr].getYear ());

}} // main method

static public void insertionSort (int listSize, StudentRec sr []){

for (int j = 1 ; j < listSize ; j++){

Page 174: 6916388 Problems and Solutions in Java

Page 172

// Find where to insert jth element.int i = 1;while (i != j &&

(sr [i].getName ()).compareTo (sr [j].getName ()) < 0){

i++;}shift (i, j, sr);

}} // insertionSort method

static public void shift (int i, int j, StudentRec sr []){

StudentRec temp = sr [j];for (int k = j ; k >= i ; k––){

sr [k] = sr [k – 1];}sr [i] = temp;

} // shift method} // C1602 class

StudentRec.java

// StudentRec.java - by R. Parteno July 99// Each object of the StudentRec class contains a record for a single student.

import java.awt.*;import java.io.*;

public class StudentRec{

protected String name;protected String address;protected String year;protected static final int RECORD_SIZE = 24;

public StudentRec (String name, String address, String year){

this.name = name;this.address = address;this.year = year;

} // StudentRec constructor

public String getName (){

return name;} // getName method

Page 175: 6916388 Problems and Solutions in Java

Page 173

public void setName (String newName){

name = newName;} // setName method

public String getAddress (){

return address;} // getAddress method

public String getYear (){

return year;} // getYear method

public static int recordSize (){

return RECORD_SIZE;} // recordSize method

} // StudentRec class

Page 176: 6916388 Problems and Solutions in Java

Page 174

Exercise #3

Two strings of n characters are to be compared to see whether the second string could beformed by permuting the characters in the first string. Analyze the efficiency of threepossible algorithms for doing this.

a. Scan the first string one character at a time and see if each character has acorresponding character in the second. Be sure to erase a character in the secondstring once it has been "used".

b. Sort the two strings and compare them character-by- character.

c. Prepare a frequency count of each character in each string and compare thecounts.

Solution

The following is not a mathematically sound proof. However, it gives the technique forcalculating the order of the operation.

Remember that:

• O (k*n) for any k = O (n)

• k * O (n) for any k = O (n)

• Lower order terms disappear. For example: O (n 2) + O (n) = O (n2)

a. For each character in the string (n), scan through the second string until you find a match(on average n/2 searches). Then shorten the string (a shift which is O(n/2)).

Total time = n * (O(n/2) + O (n/2)) = n * O(n/2) = n * O (n) = O(n2)

b. Sort two strings. This depends on the technique used to sort the strings. If we use a O(n logn) sort, then we have 2 * O (n log n) + O (n) to compare each element of the strings once.

Total time = 2 * O (n log n) + O (n) = O (n log n) + O (n) = O (n log n)

c. If we do a frequency count, we go through each string one, adding one to the count for thatletter. For each letter in the string, the operation is O (1) or O (n) for the entire string. We thencompare the two frequency counts with is O (x) where x is the number of possible letters. If werestrict ourself to ASCII, x = 256.

Total time = 2 * O (n) + O (256) = O (n) + O (256) = O (n) + O(1) = O(n)

Thus technique (c) is the best, for large n.

Page 177: 6916388 Problems and Solutions in Java

Page 175

Exercise #4A variation of the selection sort is called quadratic selection . In this sort the list of n itemsto be sorted is divided into 4 equal sized groups of n/4 each. The smallest element in eachgroup is selected and placed in a temporary array of 4 elements. From these the smallest isselected. It is then replaced by the next smallest elements from its original group untilsorting is complete. Program this algorithm. Analyze its performance. How does itcompare with selection sorting?

Solution

// Chapter #16 - Exercise #4 (C1604.java)

import java.awt.*;import hsa.Console;

public class C1604{

static Console c;static int dataList [], newList [];

static public void main (String args []){

// Create Console and Sorts objects.c = new Console ();// Create the data array.dataList = new int [100];// Create the array to store the final data.newList = new int [100];// Generate test data.c.println ("Generating a test data set...");dataGen (dataList, 100);// Show first ten items before the sort.c.println ("First 10 data items before the sort");showTen (dataList);// Call the quadratic sort.c.println ("Sorting the data set");quadSort (dataList, newList);// Show first ten items after the sort.c.println ("First 10 data items after the sort");showTen (newList);

} // main method

// dataGen generates nItem random marks from 1 to 100// and stores marks in array.static public void dataGen (int dataList [], int nItems){

for (int ctr = 0 ; ctr < nItems ; ctr++){

dataList [ctr] = (int ) (Math.random () * 100) + 1;}

} // dataGen method

Page 178: 6916388 Problems and Solutions in Java

Page 176

// showTen displays the first 10 records. This is// useful for checking that the sort is working.static public void showTen (int dataList []){

for (int ctr = 0 ; ctr < 10 ; ctr++){

c.println (dataList [ctr]);}

} // showTen method

static void quadSort (int data [], int newData []){

int smallFour [] = new int [4];int countFour [] = new int [4];int dataCtr, smallMin;int newCtr = 0;boolean sorted = false ;// Gets initial data values into the four item array and sets start// values. countFour keeps track of the number of items taken from// each quarter.for (int ctr = 0 ; ctr < 4 ; ctr++){

smallFour [ctr] = onePass (data, ctr * 25, ctr * 25 + 24);countFour [ctr] = 0;

}while (!sorted){

// Finds the smallest item in the array of four items.dataCtr = 0;smallMin = smallFour [dataCtr];for (int ctr = 1 ; ctr < 4 ; ctr++){

if (smallFour [ctr] < smallMin && countFour [ctr] < 25){

smallMin = smallFour [ctr];dataCtr = ctr;

}}// Adds the smallest item to a new array.newData [newCtr] = smallFour [dataCtr];newCtr++;// Takes the next item from the large array into the four// item array.countFour [dataCtr]++;if (countFour [dataCtr] < 25)

smallFour [dataCtr] = onePass (data, dataCtr * 25 +countFour [dataCtr], dataCtr * 25 + 24);

else if (sumFour (countFour) > 99)sorted = true;

}} // quadsort method// onePass finds the smallest number in the range from first// to last and stores it at position first. This is equivalent to one

Page 179: 6916388 Problems and Solutions in Java

Page 177

// pass of a selection sort.static public int onePass (int data [], int first, int last){

int min = data [first];int minPtr = first;int hold;if (first == last) // When range has only one item.{

return data [first];}else // When range has more than one item.{

for (int ctr = first + 1 ; ctr <= last ; ctr++){

if (data [ctr] < data [first]){

// swaphold = data [first];data [first] = data [ctr];data [ctr] = hold;

}}return data [first];

}} // onePass method

// Sums the number of data values that have been taken.static public int sumFour (int count []){

return count [0] + count [1] + count [2] + count [3];} // sumFour method

} // C1604 class

The following is not a mathematically sound proof. However, it gives the technique forcalculating the order of the operation.

a. The list is divided into four groups and copied -> O (n)

b. For each group, the smallest element in the group is selected. To select the smallest element from each group, we look through each element of the group looking for the smallest number.

-> 4 (O (n/4)) -> O (n/4) -> O (n)

c. We loop n times

c1. Select the smallest element -> O (4) -> O (1)

c2. Replace the element with the next smallest element in the group

-> O (n/4) -> O (n)

Total time O (n) + O (n) + n * (O (1) + O (n)) -> O (n) + n * O (n)

-> O (n) + O (n2) -> O (n2)

Thus this is an O (n2) sort which is not all that impressive.

Page 180: 6916388 Problems and Solutions in Java

Page 178

Chapter 17.8 Solutions

Exercise #1

A stack is a list in which new entries go at the head (or top) of the list and are said to bepushed onto the stack. Entries are removed from the top of this list and are said to bepopped from the stack. Define these operations for an ADT Stack.

push, pop, display

Write a demonstration program to push names onto the stack and pop them off the stack.Implement a Stack class using links.

Solution

// Chapter 17 - Exercise 1 (C1701)

import java.awt.*;import hsa.Console;

public class C1701{

static Console c;

static public void main (String args []){

c = new Console ();Stack st = new Stack ();String name;// This first POP on an empty stack results in a message// saying that the stack is empty.c.println ("Attempting to pop an empty stack.");name = st.pop ();if (name == null ){

c.println ("Stack is empty");}else{

c.println (name);}c.println ();// Push three names onto the stack and display.// Note the display order is reverse as a stack would be (LIFO).c.println ("Pushing Tom");st.push ("Tom");c.println ("Pushing Chris");st.push ("Chris");c.println ("Pushing Cathy");st.push ("Cathy");c.println ();

Page 181: 6916388 Problems and Solutions in Java

Page 179

// Display contents of the stack.c.println ("Displaying contents of stack");st.display (c);c.println ();// Popping stack.name = st.pop ();while (name != null ){

c.println ("Popped " + name);name = st.pop ();

}// Display the stack to show Pat's name is gone.st.display (c);

} // main method} // C1701 class

Stack.java

// The "Stack" class simulates a memory stack.

import java.awt.*;import hsa.Console;

class Stack{

protected StackNode top;

// Constructor to produce empty Stack.public Stack (){

top = null ;} // Stack constructor

public String pop (){

if (top == null ){

return null ;}else{

String popWord = top.getName ();top = top.getNext ();return popWord;

}} // pop method

Page 182: 6916388 Problems and Solutions in Java

Page 180

// Print all items in Stack.public void display (Console c){

StackNode sn = top;if (sn != null ){

do{

c.println (sn.getName ());sn = sn.next;

}while (sn != null );

}} // display method

// Add a new item assumed not already present.// Add to head of Stack.public void push (String name){

StackNode sn = new StackNode (name, top);top = sn;

} // enter method} // Stack class

StackNode.java

// The "StackNode" class.// A class for creating linked list records.

public class StackNode{

protected String name;protected StackNode next;

// Constructor that initializes name but sets next to null.public StackNode (String name){

name = name;next = null ;

} // StackNode constructor

// Constructor that initializes name and nextNode.public StackNode (String name, StackNode nextNode){

this.name = name;this.next = nextNode;

} // StackNode constructor

Page 183: 6916388 Problems and Solutions in Java

Page 181

// Method to get name in node.public String getName (){

return name;} // getName method

// Method to get next in node.public StackNode getNext (){

return next;} // getNext method

// Method to set name in node.public void setName (String name){

this.name = name;} // setName method

// Method to set next in node.public void setNext (StackNode next){

this.next = next;} // setNext method

} // StackNode class

Page 184: 6916388 Problems and Solutions in Java

Page 182

Exercise #2

A queue is a list in which new entries are placed at the end (or tail) of the queue andremoved from the first (or head) of the queue. This is a first-in-first-out (FIFO)discipline. Write a linked implementation of a Queue class with operations

enter, leave, print

Write a program to test this class.

Solution

// Chapter 17 - Exercise 2 (C1702)

import java.awt.*;import hsa.Console;

public class C1702{

static Console c;

static public void main (String args []){

c = new Console ();Queue queue = new Queue ();String name;// This first POP on an empty queue results in a message// saying that the queue is empty.c.println ("Attempting to leave an empty queue.");name = queue.leave ();if (name == null ){

c.println ("Queue is empty");}else{

c.println (name);}c.println ();// Push three names onto the queue and display.// Note the display order is the same as they were entered (FIFO).c.println ("Entering Tom");queue.enter ("Tom");c.println ("Entering Chris");queue.enter ("Chris");c.println ("Entering Cathy");queue.enter ("Cathy");c.println ();// Display contents of the queue.c.println ("Displaying contents of queue");queue.print (c);c.println ();

Page 185: 6916388 Problems and Solutions in Java

Page 183

// Popping queue.name = queue.leave ();while (name != null ){

c.println (name + " Left");name = queue.leave ();

}// Display the queue to show Pat's name is gone.queue.print (c);

} // main method} // C1702 class

Queue.java

// The "Queue" class.

import java.awt.*;import hsa.Console;

class Queue{

// Strings enter at the tail of the queue and leave from the head.protected QueueNode head, tail;

// Constructor to produce empty Queue.public Queue (){

head = tail = null ;} // Stack constructor

public String leave (){

QueueNode leavingNode;if (head == null ){

return null ;}leavingNode = head;head = head.getNext ();if (head == null ){

tail = null ;}return leavingNode.getName ();

}

Page 186: 6916388 Problems and Solutions in Java

Page 184

// Print all items in Queue.public void print (Console c){

QueueNode qn = head;while (qn != null ){

c.println (qn.getName ());qn = qn.next;

}} // print method

// Add a new item assumed not already present.// Add to head of Stack.public void enter (String name){

QueueNode qn = new QueueNode (name);if (head == null ){

head = qn;}else{

tail.setNext (qn);}tail = qn;

} // enter method} // Queue class

QueueNode.java

// The "QueueNode" class.// A class for creating selfrecords.

public class QueueNode{

protected String name;protected QueueNode next;

// Constructor that initializes name but sets next to null.public QueueNode (String name){

this.name = name;this.next = null ;

} // QueueNode constructor

// Method to get name in node.public String getName (){

return name;} // getName method

Page 187: 6916388 Problems and Solutions in Java

Page 185

// Method to get next in node.public QueueNode getNext (){

return next;} // getNext method

// Method to set name in node.public void setName (String name){

this.name = name;} // setName method

// Method to set next in node.public void setNext (QueueNode next){

this.next = next;} // setNext method

} // QueueNode class

Page 188: 6916388 Problems and Solutions in Java

Page 186

Exercise #3It is often useful to save a list in memory between one use and the next. Modify the Listclass so that the operations load and save are added. These are used to initialize the list byreading it from a file rather than initializing it as being empty. If a save operation is givenbefore leaving any program that uses the list, the list can be read from the file by a loadoperation the next time the program is used.

Solution

// Chapter 17 - Exercise 3 (C1703)

import java.awt.*;import java.io.*;import hsa.Console;

public class C1703{

static Console c;

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

c = new Console ();List lst = new List ();// Enter three names onto the list and display on screen.lst.enter ("1234", "Talbot");lst.enter ("2344", "Wilmot");lst.enter ("6742", "Desouza");c.println ("The List has 3 employee names");lst.display (c);c.println ();// Save the list to disk.c.println ("Save the list to disk");c.println ();lst.save (c);// Delete a record.c.println ("Delete employee #2344");c.println ();lst.delete ("2344");// Show the updated list.c.println ("The updated list");lst.display (c);c.println ();// Load the original list from disk.c.println ("Load the original list from disk");c.println ();lst.load (c);// Show the updated list.c.println ("The restored list");lst.display (c);c.println ();

} // main method} // C1703 class

Page 189: 6916388 Problems and Solutions in Java

Page 187

List.java

// The "List" class.

import java.io.*;import java.util.*;import hsa.Console;

class List{

protected LinkRecord first;

// Constructor to produce empty list.public List (){

first = null ;} // List constructor

// Change info for item assumed in list.public void change (String key, String info){

LinkRecord where = find (key);if (where != null )

where.setInfo (info);} // change method

// Delete item assumed already in list.public void delete (String key){

LinkRecord where;if (first.getKey ().equals (key)){

where = first;first = where.getNext ();

}else{

LinkRecord prev = first;where = prev.getNext ();while (!where.getKey ().equals (key)){

prev = where;where = prev.getNext ();

}prev.next = where.getNext ();

}} // delete method

Page 190: 6916388 Problems and Solutions in Java

Page 188

// Print all items in list.public void display (Console c){

LinkRecord p = first;if (p != null ){

do{

c.println (p.getKey () + " " + p.getInfo ());p = p.next;

}while (p != null );

}else

c.println ("There are no items in list");} // display method

// Add a new item assumed not already present.// Add to head of list.public void enter (String key, String info){

LinkRecord p = new LinkRecord (key, info, first);first = p;

} // enter method

// This method used internally. It is not exported.protected LinkRecord find (String key){

LinkRecord where = first;while (where != null && !where.getKey ().equals (key)){

where = where.getNext ();}return where;

} // find method

public String lookUp (String key){

String info;LinkRecord where = find (key);if (where != null )

info = where.getInfo ();else

info = null ;return info;

} // lookUp method

Page 191: 6916388 Problems and Solutions in Java

Page 189

public void load (Console c){

String line, empNum, empName;BufferedReader input = null ;first = null ; // first clear the exiting listtry{

input = new BufferedReader (new FileReader ("employee.txt"));line = input.readLine ();while (line != null ){

StringTokenizer inLine = new StringTokenizer (line);empNum = inLine.nextToken ();empName = inLine.nextToken ();enter (empNum, empName);line = input.readLine ();

}}catch (IOException ioe){

c.println ("Unable to open the data file...");}

} // load method

public void save (Console c) throws IOException{

PrintWriter output = new PrintWriter (new FileWriter("employee.txt"));

LinkRecord p = first;if (p != null ){

do{

output.println (p.getKey () + " " + p.getInfo ());p = p.next;

}while (p != null );

}else

c.println ("There are no items in list");output.close ();

} // save method} // List class

Page 192: 6916388 Problems and Solutions in Java

Page 190

Chapter 18.10 Solutions

Exercise #1

Write an applet that will act like the keypad of a touch-tone telephone. Display the phonenumber of the person being called at the top of the applet as the number is being entered.The applet should look like Figure 18.9.

Figure 18.9 Touch-tone Telephone Keypad

Solution

// Chapter 18 - Exercise 1 (C1801.java)

import java.applet.Applet;import java.awt.*;

public class C1801 extends Applet{

// Declare an array of buttons for the keypad.private Button num [] = new Button [12];private Panel keys;private Font f;private TextField number;String phone = "";

public void init (){

number = new TextField ("", 15);// This loop sets the lable to the same value as the button.// For example, num[4] is the 4 button.for (int ctr = 0 ; ctr < 10 ; ctr++){

num [ctr] = new Button (Integer.toString (ctr));}num [10] = new Button ("*");num [11] = new Button ("#");// Set the initial state of the text field.f = new Font ("Serif", Font.PLAIN, 15);

Page 193: 6916388 Problems and Solutions in Java

Page 191

// Set the font type.number.setFont (f);setLayout (new BorderLayout ());add ("North", number);keys = new Panel ();keys.setLayout (new GridLayout (4, 3, 2, 2));// Add the buttons to give the look of a keypad.for (int ctr = 1 ; ctr < 10 ; ctr++){

keys.add (num [ctr]);}keys.add (num [10]);keys.add (num [0]);keys.add (num [11]);add ("Center", keys);

} // init method

public boolean action (Event e, Object o){

// Test to see if a number has been pressed.for (int ctr = 0 ; ctr < 10 ; ctr++){

// If it has, add it to the phone number.if (e.target == num [ctr]){

phone = number.getText ();if (phone.length () < 7){

phone = phone.concat (Integer.toString (ctr));number.setText (phone);

}}

}return true;

} // action method} // C1801 class

Page 194: 6916388 Problems and Solutions in Java

Page 192

Exercise #2

Modify the applet of Exercise 1 so that the phone number displayed will have a dashbetween digits that represent the area code, the exchange, and the 4-digit number. Forexample, numbers might be entered as 416-555-4141 or only 555-4141. The dashes are tobe inserted by the programs as required.

Solution

// Chapter 18 - Exercise 2 (C1802.java)// NOTE: This program differs slightly from the book.// If the first digit is a 1 the program expects a long// distance number in 1-999-999-9999 format.// If the first digit is not a 1, the program expects// a local number format 999-9999

import java.applet.Applet;import java.awt.*;

public class C1802 extends Applet{

// Declare an array of buttons for the keypad.private Button num [] = new Button [12];private Panel keys;private Font f;private TextField number;StringBuffer phone;

public void init (){

number = new TextField ("", 15);

// This loop sets the lable to the same value as the button.// For example, num[4] is the 4 button.

for (int ctr = 0 ; ctr < 10 ; ctr++){

num [ctr] = new Button (Integer.toString (ctr));}num [10] = new Button ("*");num [11] = new Button ("#");

// Set the initial state of the text field.f = new Font ("Arial", Font.PLAIN, 15);

// Set the font type.number.setFont (f);setLayout (new BorderLayout ());add ("North", number);

keys = new Panel ();

Page 195: 6916388 Problems and Solutions in Java

Page 193

keys.setLayout (new GridLayout (4, 3, 2, 2));

// Add the buttons to give the look of a keypad.for (int ctr = 1 ; ctr < 10 ; ctr++){

keys.add (num [ctr]);}keys.add (num [10]);keys.add (num [0]);keys.add (num [11]);

add ("Center", keys);} // init method

public boolean action (Event e, Object o){

// Test to see if a number has been pressed.for (int ctr = 0 ; ctr < 10 ; ctr++){

// If it has, add it to the phone number.if (e.target == num [ctr]){

phone = new StringBuffer (number.getText ());// If the number is null, add the first digit.if (phone.length () == 0){

phone.append (Integer.toString (ctr));if (ctr == 1){

phone.append ('-');}

}// If the number begins with a 1, then fill in// the pattern 1.else if (phone.charAt (0) == '1' && phone.length () < 14){

phone.append (Integer.toString (ctr));if (phone.length () == 5 || phone.length () == 9)

phone.append ('-');}// Otherwise fill the pattern for a regular number 999-.else if (phone.length () < 8){

phone.append (Integer.toString (ctr));if (phone.length () == 3)

phone.append ('-');}// If the number is over 8 digits, then convert it to 999--.else if (phone.length () < 12){

Page 196: 6916388 Problems and Solutions in Java

Page 194

// Check for situation of 999-.if (phone.length () == 8){

// We now want to convert 999-to 999--.phone.insert (7, '-');

}phone.append (Integer.toString (ctr));

}// Output the updated number to the screen.number.setText (phone.toString ());

}} // for

return true;} // action method

} // C1802 class

Page 197: 6916388 Problems and Solutions in Java

Page 195

Exercise #3

Create an applet that has the user:

• enter two real numbers in two text fields,

• select a radio button to indicate the required operation: add,

subtract, multiply, or divide,

• press a button to execute the calculation,

• display the result in a third text field, and

• press a button to clear the calculator.

Solution

// Chapter 18 - Exercise 3 (C1803.java)// You can make the buttons look much "nicer" by putting each one in// a separate panel and then adding the panels to the applet.

import java.applet.Applet;import java.awt.*;

public class C1803 extends Applet{

private Panel numbers, oper;private Button clear, calculate;private TextField number1, number2, number3;private Checkbox addn, subtract, multiply, divide;private CheckboxGroup operations;StringBuffer phone;Double d;double n1, n2, n3 ;

public void init (){

number1 = new TextField ("", 15);number2 = new TextField ("", 15);number3 = new TextField ("", 15);clear = new Button ("Clear");calculate = new Button ("Calculate");numbers = new Panel ();numbers.setLayout (new GridLayout (2, 3, 2, 2));numbers.add (number1);numbers.add (number2);numbers.add (number3);numbers.add (calculate);numbers.add (clear);oper = new Panel ();oper.setLayout (new GridLayout (1, 4, 2, 2));// Set up a group of Checkboxes for operations.operations = new CheckboxGroup ();

Page 198: 6916388 Problems and Solutions in Java

Page 196

// Check add radio button only to start.addn = new Checkbox ("Add", operations, true);subtract = new Checkbox ("Subtract", operations, false );multiply = new Checkbox ("Multiply", operations, false );divide = new Checkbox ("Divide", operations, false );// Add each object to the appropriate panel.oper.add (addn);oper.add (subtract);oper.add (multiply);oper.add (divide);setLayout (new BorderLayout ());add ("Center", numbers);add ("South", oper);

} // init method

public boolean action (Event e, Object o){

if (e.target == clear){

number1.setText ("");number2.setText ("");number3.setText ("");

}else if (e.target == calculate){

d = Double.valueOf (number1.getText ());n1 = d.doubleValue ();d = Double.valueOf (number2.getText ());n2 = d.doubleValue ();if (addn.getState () == true)

n3 = n1 + n2;else if (subtract.getState () == true)

n3 = n1 – n2;else if (multiply.getState () == true)

n3 = n1 * n2;else

n3 = n1 / n2;number3.setText (Double.toString (n3));

}return true;

} // action method} // C1803 class

Page 199: 6916388 Problems and Solutions in Java

Page 197

Exercise #4Create an applet that has three radio buttons used to select the color (red, green, or blue)for drawing with a ballpoint pen effect on a canvas in the applet.

Solution

// Chapter 18 - Exercise 4 (C1804.java)

import java.applet.Applet;import java.awt.*;

public class C1804 extends Applet{

private Checkbox red, blue, green;private CheckboxGroup colours;private Panel pColour;final int RADIUS = 5;Color clr = Color.red;

public void init (){

// Set up a group of Checkboxes for colours.colours = new CheckboxGroup ();// Check red radio button only to start.red = new Checkbox ("Red", colours, true);blue = new Checkbox ("Blue", colours, false );green = new Checkbox ("Green", colours, false );// Create the panel.pColour = new Panel ();// Add each object to the appropriate panel.pColour.add (red);pColour.add (blue);pColour.add (green);setLayout (new BorderLayout ());// Add the panels to the applet.add ("South", pColour);

} // init method

public boolean action (Event e, Object o){

if (e.target instanceof Checkbox){

// Read the state of the colour radio buttons.if (red.getState () == true)

clr = Color.red;else if (blue.getState () == true)

clr = Color.blue;else

clr = Color.green;}return true;

} // action method

Page 200: 6916388 Problems and Solutions in Java

Page 198

protected void drawBall (Graphics g, int x, int y, int radius, Color clr){

g.setColor (clr);g.fillOval (x – radius, y – radius , 2 * radius, 2 * radius);

} // drawBall method

public boolean mouseDown (Event e, int x, int y){

Graphics g = getGraphics ();drawBall (g, x, y, RADIUS, clr);return true;

} // mouseDown method

public boolean mouseDrag (Event e, int x, int y){

Graphics g = getGraphics ();drawBall (g, x, y, RADIUS, clr);return true;

} // mouseDown method} // C1804 class

Page 201: 6916388 Problems and Solutions in Java

Page 199

Exercise #5

Write an applet to draw rectangles in the applet. The upper-left corner of the rectangle isto be established by pressing the mouse button down. The mouse is then dragged to thelower-right corner of the wanted rectangle and released. Arrange that several rectanglescan be drawn, one after the other, and remain on the screen.

Solution

// Chapter 18 - Exercise 5 (C1805.java)

import java.applet.Applet;import java.awt.*;

public class C1805 extends Applet{

private int x1, y1;private boolean start;

protected void drawRect (Graphics g, int x1, int y1, int x2, int y2,Color clr)

{g.setColor (clr);if (x2 > x1){

if (y2 > y1)g.drawRect (x1, y1, Math.abs (x1 – x2), Math.abs (y1 – y2));

elseg.drawRect (x1, y2, Math.abs (x1 – x2), Math.abs (y1 – y2));

}else{

if (y2 > y1)g.drawRect (x2, y1, Math.abs (x1 – x2), Math.abs (y1 – y2));

elseg.drawRect (x2, y2, Math.abs (x1 – x2), Math.abs (y1 – y2));

}} // drawRect method

public boolean mouseDown (Event e, int x, int y){

start = true;// Record x y location.x1 = x;y1 = y;return true;

} // mouseDown method

Page 202: 6916388 Problems and Solutions in Java

Page 200

public boolean mouseUp (Event e, int x, int y){

if (start){

Graphics g = getGraphics ();drawRect (g, x1, y1, x, y, Color.red);

}return true;

} // mouseUp method} // C1805 class

Page 203: 6916388 Problems and Solutions in Java

Page 201

Exercise #6

Modify the applet of Exercise 5 so that a rectangle is drawn as soon as the mouse starts tobe dragged but is constantly updated so that it is replaced by a new rectangle as the mouseis dragged to a new point. Hint: to erase the old rectangle it must be drawn in thebackground color before the new rectangle is drawn.

Solution

// Chapter 18 - Exercise 6 (C1806.java)

import java.applet.Applet;import java.awt.*;

public class C1806 extends Applet{

private int x1, y1, x2, y2;private boolean start;

protected void drawRect (Graphics g, int x1, int y1, int x2, int y2,Color clr)

{g.setColor (clr);if (x2 > x1){

if (y2 > y1)g.drawRect (x1, y1, Math.abs (x1 – x2), Math.abs (y1 – y2));

elseg.drawRect (x1, y2, Math.abs (x1 – x2), Math.abs (y1 – y2));

}else{

if (y2 > y1)g.drawRect (x2, y1, Math.abs (x1 – x2), Math.abs (y1 – y2));

elseg.drawRect (x2, y2, Math.abs (x1 – x2), Math.abs (y1 – y2));

}} // drawRect method

public boolean mouseDown (Event e, int x, int y){

start = true;// Record x y location.x1 = x;y1 = y;return true;

} // mouseDown method

Page 204: 6916388 Problems and Solutions in Java

Page 202

public boolean mouseDrag (Event e, int x, int y){

Graphics g = getGraphics ();if (!start){

// Erase previous rectangle.drawRect (g, x1, y1, x2, y2, Color.white);

}else{

start = false ;}// Draw the new rectangle.x2 = x;y2 = y;drawRect (g, x1, y1, x2, y2, Color.red);return true;

} // mouseDrag method */} // C1806 class

Page 205: 6916388 Problems and Solutions in Java

Page 203

Exercise #7

Modify the PaintShape and PaintCanvas classes to allow a fourth color for drawing theshapes.

Solution

// The "C1807" class.

import java.awt.*;

public class C1807 extends Frame{

Button clearButton;MenuItem quitItem;CheckboxMenuItem ovalItem, rectItem, redItem, greenItem, blueItem,

cyanItem;PaintCanvas drawingSurface;

// Constructorpublic C1807 (){

super ("Paint");// Create the menu items.quitItem = new MenuItem ("Quit Paint");ovalItem = new CheckboxMenuItem ("Oval");rectItem = new CheckboxMenuItem ("Rectangle");redItem = new CheckboxMenuItem ("Red");greenItem = new CheckboxMenuItem ("Green");blueItem = new CheckboxMenuItem ("Blue");cyanItem = new CheckboxMenuItem ("Cyan");// Place the menu items into menus.Menu fileMenu = new Menu ("File");fileMenu.add (quitItem);Menu shapeMenu = new Menu ("Shape");shapeMenu.add (ovalItem);shapeMenu.add (rectItem);Menu colorMenu = new Menu ("Color");colorMenu.add (redItem);colorMenu.add (greenItem);colorMenu.add (blueItem);colorMenu.add (cyanItem);// Place the menus into the menu bar.MenuBar myMenus = new MenuBar ();myMenus.add (fileMenu);myMenus.add (shapeMenu);myMenus.add (colorMenu);setMenuBar (myMenus);setBackground (Color.gray);// We put the clear button in a panel to make it a small size.clearButton = new Button ("Clear");Panel p = new Panel ();

Page 206: 6916388 Problems and Solutions in Java

Page 204

p.add (clearButton);add ("North", p);drawingSurface = new PaintCanvas ();add ("South", drawingSurface);// Set the default values for shape and color.drawingSurface.currentShape = drawingSurface.RECTANGLE;drawingSurface.currentColor = Color.red;rectItem.setState (true);redItem.setState (true);pack ();show ();

} // PaintShape constructor

// Handles button presses and menu item selection.public boolean action (Event e, Object arg){

if (e.target == clearButton){

drawingSurface.clear ();}if (e.target == quitItem){

hide ();System.exit (0);

}else if (e.target == ovalItem){

drawingSurface.currentShape = drawingSurface.OVAL;ovalItem.setState (true);rectItem.setState (false );

}else if (e.target == rectItem){

drawingSurface.currentShape = drawingSurface.RECTANGLE;ovalItem.setState (false );rectItem.setState (true);

}else if (e.target == redItem){

drawingSurface.currentColor = Color.red;redItem.setState (true);greenItem.setState (false );blueItem.setState (false );cyanItem.setState (false );

}else if (e.target == greenItem){

drawingSurface.currentColor = Color.green;redItem.setState (false );greenItem.setState (true);blueItem.setState (false );cyanItem.setState (false );

}

Page 207: 6916388 Problems and Solutions in Java

Page 205

else if (e.target == blueItem){

drawingSurface.currentColor = Color.blue;redItem.setState (false );greenItem.setState (false );blueItem.setState (true);cyanItem.setState (false );

}else if (e.target == cyanItem){

drawingSurface.currentColor = Color.cyan;redItem.setState (false );greenItem.setState (false );blueItem.setState (false );cyanItem.setState (true);

}else{

return false ;}return true;

} // action method

// Overrides the handleEvent method. It handles window being closed.public boolean handleEvent (Event evt){

switch (evt.id){

case Event.WINDOW_DESTROY:hide ();System.exit (0);return true;

}return super.handleEvent (evt);

} // handleEvent method

public static void main (String args []){

new C1807 ();} // main method

} // C1807 class

Page 208: 6916388 Problems and Solutions in Java

Page 206

Exercise #8

Create an application program with menus that allows the user to choose a text font, apoint size, and a color for displaying the text "Happy Birthday" in the window beginningat a point at which the mouse is clicked.

Solution

// Chapter 18 Exercise 8 (C1808.java)

import java.awt.*;

public class C1808 extends Frame{

Button clearButton;MenuItem quitItem;CheckboxMenuItem serifItem , sansSerifItem, monoSpacedItem;CheckboxMenuItem f10Item, f12Item, f14Item, redItem, greenItem, blueItem;C1808c drawingSurface;String fontName;int fontSize;private Font f;

// Constructorpublic C1808 (){

super ("Paint");// Create the menu items.quitItem = new MenuItem ("Quit");serifItem = new CheckboxMenuItem ("Serif");sansSerifItem = new CheckboxMenuItem ("SansSerif");monoSpacedItem = new CheckboxMenuItem ("Monospaced");f10Item = new CheckboxMenuItem ("10 pt");f12Item = new CheckboxMenuItem ("12 pt");f14Item = new CheckboxMenuItem ("14 pt");redItem = new CheckboxMenuItem ("Red");greenItem = new CheckboxMenuItem ("Green");blueItem = new CheckboxMenuItem ("Blue");// Place the menu items into menus.Menu fileMenu = new Menu ("File");fileMenu.add (quitItem);Menu fontMenu = new Menu ("Font");fontMenu.add (serifItem);fontMenu.add (sansSerifItem);fontMenu.add (monoSpacedItem);Menu pointMenu = new Menu ("Size");pointMenu.add (f10Item);pointMenu.add (f12Item);pointMenu.add (f14Item);Menu colorMenu = new Menu ("Color");colorMenu.add (redItem);colorMenu.add (greenItem);

Page 209: 6916388 Problems and Solutions in Java

Page 207

colorMenu.add (blueItem);// Place the menus into the menu bar.MenuBar myMenus = new MenuBar ();myMenus.add (fileMenu);myMenus.add (fontMenu);myMenus.add (pointMenu);myMenus.add (colorMenu);setMenuBar (myMenus);setBackground (Color.gray);// We put the clear button in a panel to make it a small size.clearButton = new Button ("Clear");Panel p = new Panel ();p.add (clearButton);add ("North", p);drawingSurface = new C1808c ();add ("South", drawingSurface);// Set the default values for shape and color.drawingSurface.currentShape = drawingSurface.RECTANGLE;drawingSurface.setForeground (Color.red);serifItem.setState (true);fontName = "Serif";f10Item.setState (true);fontSize = 10;redItem.setState (true);drawingSurface.setFont (new Font (fontName, Font.BOLD, fontSize));pack ();show ();

} // PaintShape constructor

// Handles button presses and menu item selection.public boolean action (Event e, Object arg){

if (e.target == clearButton){

drawingSurface.clear ();}if (e.target == quitItem){

hide ();System.exit (0);

}else if (e.target == serifItem){

fontName = "Serif";serifItem.setState (true);sansSerifItem.setState (false );monoSpacedItem.setState (false );

}

Page 210: 6916388 Problems and Solutions in Java

Page 208

else if (e.target == sansSerifItem){

fontName = "SansSerif";serifItem.setState (false );sansSerifItem.setState (true);monoSpacedItem.setState (false );

}else if (e.target == monoSpacedItem){

fontName = "Monospaced";serifItem.setState (false );sansSerifItem.setState (false );monoSpacedItem.setState (true);

}else if (e.target == f10Item){

fontSize = 10;f10Item.setState (true);f12Item.setState (false );f14Item.setState (false );

}else if (e.target == f12Item){

fontSize = 12;f10Item.setState (false );f12Item.setState (true);f14Item.setState (false );

}else if (e.target == f14Item){

fontSize = 14;f10Item.setState (false );f12Item.setState (false );f14Item.setState (true);

}else if (e.target == redItem){

drawingSurface.setForeground (Color.red);redItem.setState (true);greenItem.setState (false );blueItem.setState (false );

}else if (e.target == greenItem){

drawingSurface.setForeground (Color.green);redItem.setState (false );greenItem.setState (true);blueItem.setState (false );

}

Page 211: 6916388 Problems and Solutions in Java

Page 209

else if (e.target == blueItem){

drawingSurface.setForeground (Color.blue);redItem.setState (false );greenItem.setState (false );blueItem.setState (true);

}else{

return false ;}drawingSurface.setFont (new Font (fontName, Font.BOLD, fontSize));return true;

} // action method

// Overrides the handleEvent method. It handles window being closed.public boolean handleEvent (Event evt){

switch (evt.id){

case Event.WINDOW_DESTROY:hide ();System.exit (0);return true;

}return super.handleEvent (evt);

} // handleEvent method

public static void main (String args []){

new C1808 ();} // main method

} // C1808 class

C1808c.java

// The "C1808c" class.

import java.awt.*;

class C1808c extends Canvas{

static final int OVAL = 1;static final int RECTANGLE = 2;int currentShape;Color currentColor;protected int startX, startY, currentX, currentY;

Page 212: 6916388 Problems and Solutions in Java

Page 210

public C1808c (){

resize (400, 400);setBackground (Color.white);

} // C1808c constructor

// Clears the canvas.protected void clear (){

Graphics g = getGraphics ();g.clearRect (0, 0, size ().width, size ().height);

} // clear method

protected void drawShape (int cornerX, int cornerY){

Graphics g = getGraphics ();int x, y, shapeWidth, shapeHeight;// Be sure shapeWidth and shapeHeight are always positive.x = Math.min (startX, cornerX);shapeWidth = Math.abs (cornerX – startX);y = Math.min (startY, cornerY);shapeHeight = Math.abs (cornerY – startY);// Now draw the shape outline. Use XOR mode so if the shape// outline is already drawn there this erases it.g.setXORMode (Color.white);if (currentShape == RECTANGLE){

g.drawRect (x, y, shapeWidth, shapeHeight);}else{

g.drawOval (x, y, shapeWidth, shapeHeight);}

} // drawShape method

public boolean mouseDown (Event e, int x, int y){

Graphics g = getGraphics ();g.drawString ("Happy Birthday!!", x, y);return true;

} // mouseDown method} // C1808c class