Solution Manual For FUNDAMENTALS OF JAVA AP® Computer Science Essentials 4Th Edition By Kenneth Lambert and Martin Osborne

<< Solution Manual For Principles Of Managerial Finance 13Th Edition By Lawrence J. Gitman Sociology The Essentials 8th Edition By Andersen-Test Bank >>
Product Code: 222
Availability: In Stock
Price: $24.99
Qty:     - OR -   Add to Wish List
Add to Compare

Solution Manual For FUNDAMENTALS OF JAVA AP® Computer Science Essentials 4Th Edition By Kenneth Lambert and Martin Osborne

Description

COMPLETE TEXT BOOK SOLUTION WITH ANSWERS

 

 

ORDER WILL BE DELIVER WITHIN FEW HOURS

 

 

SAMPLE QUESTIONS

 

 

FUNDAMENTALS

OF JAVA

 

AP Computer Science Essentials,

Fourth Edition

 

Kenneth Lambert and Martin Osborne

 

 

 

 

Chapter 1:

Background

 

EXERCISE 1.6

  1. In what way is programming like planning the construction of a house?
  2. An object-oriented program is a set of objects that interact by sending messages to each other. Explain.
  3. What is a class, and how does it relate to objects in an object-oriented program?
  4. Explain the concept of inheritance with an example.
  5. Explain the concept of information hiding with an example.

REVIEW Questions

WRITTEN QUESTIONS

Write a brief answer to each of the following questions.

  1. What are the three major hardware components of a computer?
  2. Name three input devices.
  3. Name two output devices.
  4. What is the difference between application software and system software?
  5. Name a first-generation programming language, a second-generation programming language,

and a third-generation programming language.

FILL IN THE BLANK

Complete the following sentences by writing the correct word or words in the blanks provided.

  1. All information used by a computer is represented using notation.
  2. The phase of the software life cycle is also called the coding phase.
  3. More than half of the cost of developing software goes to the phase of the software

life cycle.

  1. ACM stands for .
  2. Copyright law is designed to give fair use to the public and to protect the rights of

and .

PROJECTS

PROJECT 1-1

Take some time to become familiar with the architecture of the computer you will use for this

course. Describe your hardware and software using the following guidelines:

What hardware components make up your system?

How much memory does your system have?

What are the specifications of your CPU? (Do you know its speed and what kind of microprocessor

it has?)

What operating system are you using? What version of that operating system is your computer

currently running?

What major software applications are loaded on your system?

CRITICAL Thinking

You have just written some software that you would like to sell. Your friend suggests that

you copyright your software. Discuss why this might be a good idea.

 

Chapter 2:

 First Java Programs

EXERCISE 2.1

  1. What is a portable program?
  2. Describe two features of Java that make it a better language than C++.
  3. What is a thread? Describe how threads might be used in a program.

EXERCISE 2.2

  1. What does JVM stand for?
  2. What is byte code? Describe how the JVM uses byte code.
  3. What is an applet? Describe how applets are used.

EXERCISE 2.4

  1. Give a short definition of program.
  2. What is the effect of the message println?
  3. Describe how to use the System.out object.
  4. Write a sequence of statements to display your name, address, and phone number in the terminal

window.

EXERCISE 2.5

  1. Name the three steps in writing and running a program.
  2. What are compile-time errors?
  3. Find the compile-time errors in the following statements:
  4. System.out.println(Here is an error);
  5. System.out.println(Here is another error;
  6. Why is readability a desirable characteristic of a program?

EXERCISE 2.6

  1. What is a variable in a program and how is it used?
  2. Describe the role of the assignment (=) operator in a program.
  3. What is a Scanner object?
  4. Explain the difference between a variable of type double and a variable of type Scanner.
  5. Describe the difference between print and println, and give an appropriate example of the use

of each.

EXERCISE 2.7

  1. Write the integer values of red, green, and blue for the following RGB colors:
  2. white
  3. black
  4. highest intensity blue
  5. medium gray
  6. Describe the roles and responsibilities of a frame, a panel, and a layout manager in a GUI application.
  7. Where are panels displayed when a border layout is used to control their placement in a window?
  8. Write a code segment that would be used to set the layout for adding panels to a 5-by-5 grid in a window.

You may assume that the panels content pane is named pane.

REVIEWQuestions

WRITTEN QUESTIONS

Write a brief answer to each of the following questions.

  1. List three reasons why Java is an important programming language.
  2. What is byte code?
  3. What is the JVM?
  4. List two objects that are used for terminal input and output in Java programs.
  5. Give examples of two compile-time errors.
  6. What steps must be followed to run a Java program?
  7. Why do programmers use program comments in their code?
  8. What is the purpose of an import statement in a Java program?

FILL IN THE BLANK

Complete the following sentences by writing the correct word or words in the blanks provided.

  1. Two user interface styles are and .
  2. The message is used to output data to the terminal window.
  3. The message is used to input a number from the keyboard.
  4. A(n) names a place where data can be stored in a Java program.
  5. A(n) stores the value of the expression in the variable.
  6. Programs manipulate objects by sending them .

PROJECTS

Beginning with this chapter, we conclude each chapter with a set of programming problems

and activities. We want to emphasize that programming is not just coding. Thus, a complete

solution to each exercise in this section would include not just a set of .java and .class files for the

program but also a report that covers the analysis, design, and results of testing the program.

Ideally, you would do analysis and design before coding, and perhaps turn in this work for

review before coding proceeds. How this is done depends on the size of the class and the time

available to the instructor. In any case, when you see the words write a program that . . ., you

should at least pause to reflect on the nature of the problem before coding the solution. For

example, your analysis might consist of a description of how the program would be used.

PROJECT 2-1

Write a program that displays your name, address, and telephone number.

PROJECT 2-2

A yield sign encloses the word YIELD within a triangle. Write a program that displays a yield

sign. (Use stars to represent the sides of the triangle.)

Chapter 2 First Java Programs 5 5

PROJECT 2-3

Write a program that takes as input a number of kilometers and prints the corresponding

number of nautical miles. You may rely on the following items of information:

A kilometer represents 1/10,000 of the distance between the North Pole and the equator.

There are 90 degrees, containing 60 minutes of arc each, between the North Pole and the

equator.

A nautical mile is 1 minute of an arc.

PROJECT 2-4

Write a program that calculates and prints the number of minutes in a year.

PROJECT 2-5

An objects momentum is its mass multiplied by its velocity. Write a program that expects an

objects mass (in kilograms) and velocity (in meters per second) as inputs and prints its momentum.

PROJECT 2-6

National flags are displayed on various Web sites, such as http://flagspot.net/flags/. The flags

of France, Mauritius, and Bulgaria consist of flat, colored areas. Write separate programs that

display these flags.

PROJECT 2-7

Write a program that displays a 3-by-3 grid of black and white rectangles. The rectangles

should be positioned so that no two rectangles of the same color are adjacent to each other.

CRITICALThinking

You have an idea for a program that will help the local pizza shop handle takeout orders.

Your friend suggests an interview with the shops owner to discuss her user requirements before

you get started on the program. Explain why this is a good suggestion, and list the questions you

would ask the owner to help you determine the user requirements.

 

 

Chapter 3:

Syntax, Errors, and Debugging

 

EXERCISE 3.1

  1. What is the vocabulary of a language? Give an example of an item in the vocabulary of Java.
  2. Give an example of a syntax rule in Java.
  3. What does the expression (x + y) * z mean?
  4. Describe two differences between programming languages and natural languages.

EXERCISE 3.2 Continued

  1. Convert the following floating-point numbers to exponential notation:
  2. 23.5
  3. 0.046
  4. Convert the following numbers from exponential notation to floating-point notation:
  5. 32.21E4
  6. 55.6E3
  7. Give two examples of string literals.

EXERCISE 3.2 Continued

  1. Why is a variable called a variable?
  2. Return to the programs in Chapter 2 and find an example of each of the different types of variables.

Which of the types listed in this subsection are not included?

EXERCISE 3.2 Continued

  1. Declare a floating-point variable called payRate and simultaneously initialize it to $35.67.
  2. Declare three integer variables (a, b, c) in a single declaration and simultaneously initialize b to 4.
  3. Give two examples of data that cannot be stored in a variable of type int.
  4. There are approximately 2.2 pounds in a kilogram. Name and declare a constant to represent this value.

Assignment Statements

An assignment statement has the following form:

=;

where the value of the expression on the right is assigned to the variable on the left. For instance,

doublecelsius,fahrenheit;

Stringname;

Scannerreader;

...

fahrenheit=reader.nextDouble();

celsius=(fahrenheit-32.0)*5.0/9.0;

name=BillSmith;

reader=newScanner(System.in);

Arithmetic Expressions

An arithmetic expression consists of operands and operators combined in a manner familiar

from algebra. The usual rules apply:

Multiplication and division are evaluated before addition and subtraction; that is, multiplication

and division have higher precedence than addition and subtraction.

Operators of equal precedence are evaluated from left to right.

Parentheses can be used to change the order of evaluation.

Unlike in algebra, multiplication in Java must be indicated explicitly: thus, a * b cannot be

written as ab. Binary operators are placed between their operands (a * b, for example), whereas

unary operators are placed before their operands (-a, for example). Table 3-4 shows several

operands from the conversion program in Chapter 2, and Table 3-5 shows some common operators

and their precedence.

EXERCISE 3.2 Continued

  1. Assume that the integer variable x is 5 and the integer variable y is 10. Give the values of the following

expressions:

  1. x + y * 2
  2. x y + 2
  3. (x + y) * 2
  4. y % x
  5. Find the syntax errors in the following expressions:
  6. a * b + c
  7. (a + b) * c)
  8. ()

Maximum, Minimum, and Arithmetic Overflow

Numeric data types in any programming language support a finite range of values. For example,

values of type int in Java range from a minimum of 2,147,483,648 to a maximum of

2,147,483,647. Instead of having to remember these numbers, the programmer can refer to them

with the constants Integer.MIN_VALUE and Integer.MAX_VALUE, respectively. The same constants

are included in the Double class for the bounds of double values.

It is natural to ask what would happen if a program tried to add 1 to the maximum integer

value. This would result in a condition known as arithmetic overflow. Subtracting 1 from the

minimum value would produce the same error. Programs written in some languages would halt

with a run-time error, whereas others would continue after ruining part of the computers operating

system. The JVM simply inverts the sign of the number and allows the program to continue.

Thus, adding 1 to Integer.MAX_VALUE would produce Integer.MIN_VALUE. So, if you

see large negative integers in your programs output, you might have this type of error.

Mixed-Mode Arithmetic

When working with a handheld calculator, we do not give much thought to the fact that we

intermix integers and floating-point numbers. This is called mixed-mode arithmetic. For

instance, if a circle has radius 3, we compute the area as follows:

3.14*3*3

In Java, when there is a binary operation on operands of different numeric types, the less

inclusive type (int) is temporarily and automatically converted to the more inclusive type

(double) before the operation is performed. Thus, in

doubled;

d=5.0/2;

the value of d is computed as 5.0/2.0, yielding 2.5. However, problems can arise when using

mixed-mode arithmetic. For instance

3/2*5.0 yields 1*5.0 yields 5.0

whereas

3/2.0*5 yields 1.5*5 yields 7.5

Chapter 3 Syntax, Errors, and Debugging 6 7

Mixed-mode assignments are also allowed, provided the variable on the left is of a more

inclusive type than the expression on the right. Otherwise, a syntax error occurs, as shown in the

following code segment:

doubled;

inti;

i=45;OK, because we assign an int to an int.

d=i;OK, because d is more inclusive than i. The value 45.0 is stored in d.

i=d;Syntax error because i is less inclusive than d.

EXERCISE 3.2 Continued

  1. Assume that x is 4.5 and y is 2. Write the values of the following expressions:
  2. x / y
  3. y / x
  4. x % y
  5. Assume that x and y are of type double and z is of type int. For each of the following assignment

statements, state which are valid and which produce syntax errors:

  1. x = z
  2. x = y * z
  3. z = x + y

Casting to int and double

The difficulties associated with mixed-mode arithmetic can be circumvented using a technique

called casting, which allows one data type to be explicitly converted to another. For

instance, consider the following example:

inti;

doubled;

i=(int)3.14;iequals3,truncationtoward0

d=(double)5/4;d equals1.25

The cast operator, either (int) or (double), appears immediately before the expression it is

supposed to convert. The (int) cast simply throws away the digits after the decimal point,

which has the effect of truncation toward 0.

Precedence

The cast operator has high precedence (see Table 3-5) and must be used with care, as illustrated

in the following code:

doublex,y;

x=(double)5/4; xequals5.0/4equals1.25

y=(double)(5/4); yequals(double)(1)equals1.0

Rounding

The cast operator is useful for rounding floating-point numbers to the nearest integer:

intm,n;

doublex,y;

x=...; somepositivevalueisassignedtox

m=(int)(x+0.5);

y=-...; somenegativevalueisassignedtoy

n=(int)(x-0.5);

Other numeric casts such as (char) and (float) are discussed in Appendix B.

EXERCISE 3.2 Continued

  1. Assume that x is of type double and y is of type int. Also assume that x is 4.5 and y is 2. Write the values

of the following expressions:

  1. (int) x * y
  2. (int) (x * y)
  3. Assume that x is of type double and y is of type int. Write a statement that assigns the value contained

in x to y after rounding this value to the nearest whole number.

String Expressions and Methods

Strings are used in programs in a variety of ways. As already seen, they can be used as literals

or assigned to variables. Now we see that they can be combined in expressions using the concatenation

operator, and they also can be sent messages.

Simple Concatenation

The concatenation operator uses the plus symbol (+). The following is an example:

StringfirstName,//declarefourstring

lastName,//variables

fullName,

lastThenFirst;

firstName=Bill;//initializefirstName

lastName=Smith;//initializelastName

fullName=firstName++lastName;//yieldsBillSmith

lastThenFirst=lastName+,+firstName;//yieldsSmith,Bill

Concatenating Strings and Numbers

Strings also can be concatenated to numbers. When this occurs, the number is automatically

converted to a string before the concatenation operator is applied:

Stringmessage;

intx=20,y=35;

Chapter 3 Syntax, Errors, and Debugging 6 9

message=Billsold+x+andSylviasold+y+subscriptions.;

//yieldsBillsold20andSylviasold35subscriptions.

Precedence of Concatenation

The concatenation operator has the same precedence as addition, which can lead to unexpected

results:

number+3+4_number3+4_number34

number+(3+4)_number+7_number7

number+3*4_number+12_number12

3+4+number_7+number_7number

Escape Character

String literals are delimited by quotation marks (), which presents a dilemma when

quotation marks are supposed to appear inside a string. Placing a special character before the

quotation mark, indicating the quotation mark is to be taken literally and not as a delimiter,

solves the problem. This special character, also called the escape character, is a back slash (\).

message=Asthetrainleftthestation,+

theconductoryelled,\Allaboard.\;

Other Uses for the Escape Character

The escape character also is used when including other special characters in string literals. The

sequence backslash-t ( ) indicates a tab character, and backslash-n ( ) indicates a newline character.

These special sequences involving the backslash character are called escape sequences. The following

code gives an example of the use of escape sequences followed by the output generated by the code:

Code

System.out.print(Theroomwasfullofanimals: +

dogs, cats,and chimpanzees. ;

Output

Theroomwasfullofanimals:

dogs,

cats,and

chimpanzees.

Escaping the Escape Character

In solving one problem, we have introduced another. The backslash is the designated escape

character, but sometimes a string must contain a backslash. This is accomplished by placing two

backslashes in sequence:

path=C:\Java\Ch3.doc;_yieldsthestringC:\Java\Ch3.doc

There are several other escape sequences, but we omit them from this discussion. (See

Appendix B for further details.)

The length Method

Strings are objects and implement several methods. In this chapter, we consider only the

length method and defer discussions of others until Chapter 7. A string returns its length in

response to a length message:

StringtheString;

inttheLength;

theString=Thecatsatonthemat.;

theLength=theString.length();_yields23

EXERCISE 3.2 Continued

  1. Assume that x refers to the string Wizard and y refers to the string Java. Write the values of the

following expressions:

  1. y + x
  2. y + y.length() + x
  3. y + + x +
  4. Declare a variable of type String called myInfo and initialize it to your name, address, and telephone

number. Each item of information in this string should be followed by a newline character.

Methods, Messages, and Signatures

Classes implement methods, and objects are instances of classes. An object can respond to a

message only if its class implements a corresponding method. To correspond, the method must

have the same name as the message. Thus a pen object responds to the move message because the

StandardPen class defines a move method.

Messages are sometimes accompanied by parameters and sometimes not:

doublex=reader.nextDouble(); //Noparametersexpected

System.out.println(50.5);//Oneparameterexpected

The parameters included when a message is sent must match exactly in number and type the

parameters expected by the method. For instance, the Math.sqrt method expects a single parameter

of type double.

doubled=24.6;

Math.sqrt(d);//Perfect!Aparameteroftypedoubleisexpected.

Math.sqrt(2.0*d);//Perfect!Theexpressionyieldsadouble.

Math.sqrt(4);//Fine!Integerscanstandinfordoubles.

Math.sqrt();//Error!Aparameterisneeded.

Math.sqrt(6.7,3.4);//Error!Oneparameteronlyplease.

Math.sqrt(far);//Error!AstringparameterisNOTacceptable.

Chapter 3 Syntax, Errors, and Debugging 7 1

Some methods return a value and others do not. The println method does not return a

value; however, the method nextDouble in class Scanner does:

Scannerreader=newScanner();

doublex;

x=reader.nextDouble();//Returnsthenumberenteredbytheuser.

To use a method successfully, we must know

What type of value it returns

Its name

The number and type of the parameters it expects

A methods name and the types and number of its parameters are called the methods

signature. From now on, when we introduce a new class, we will make a point of listing method

signatures together with brief descriptions of what the methods do. Following are two examples,

the first from the Scanner class and the second from the PrintStream class:

doublenextDouble()Returnsadoubleenteredbytheuseratthe

keyboard.

voidprintln(doublen)Writesntotheprintstream.

The word void indicates that the method does not return a value.

EXERCISE 3.2 Continued

  1. What is the difference between a message and a method?
  2. Describe the purpose of each item of information that appears in a methods signature.

User-Defined Symbols

Variable and program names are examples of user-defined symbols. You will see other examples

later in the book. We now explain the rules for forming or naming user-defined symbols.

These names must consist of a letter followed by a sequence of letters and/or digits. Letters are

defined to be

A Z

a z

_ and $

Symbols that denote letters in several languages other than English

Digits are the characters 0 9. Names are case-sensitive; thus, celsius and Celsius are

different names.

Some words cannot be employed as user-defined symbols. These words are called keywords

or reserved words because they have special meaning in Java. Table 3-7 shows a list of Javas

reserved words. You will encounter most of them by the end of the book. They appear in blue in

program code examples. These words are case-sensitive also, thus import is a reserved word

but Import and IMPORT are not.

EXERCISE 3.2 Continued

  1. State whether each of the following are valid or invalid user-defined symbols in Java:
  2. pricePerSquareInch
  3. student2
  4. 2GuysFromLexington
  5. PI
  6. allDone?
  7. Write names for the following items that follow good programming practice:
  8. A variable that represents the diameter of a circle
  9. A constant that represents the standard deduction for an income tax return
  10. A method that draws a rectangle

EXERCISE 3.2 Continued

  1. Describe the role of the items x, y, and Z in the statement import x.y.z;.
  2. What happens when the computer executes the statement import x.y.*;?

EXERCISE 3.3

  1. Write code segments that perform the following tasks:
  2. Prompt the user for an hourly wage and read the wage into a double variable wage.
  3. Prompt the user for a Social Security number and read this value into the String variable ssn.
  4. What is the purpose of the method nextInt()?
  5. Explain what happens when a program reads a number from the keyboard and then attempts to read

a line of text from the keyboard.

EXERCISE 3.4

  1. Describe the difference between an end-of-line comment and a multiline comment.
  2. State two rules of thumb for writing appropriate comments in a program.

EXERCISE 3.5 Continued

  1. State the type of error (compile-time, run-time, or logic) that occurs in each of the following pieces of code:
  2. x = y / 0
  3. x + y = z
  4. area = length + width

EXERCISE 3.5 Continued

  1. State the type of error (compile-time, run-time, or logic) that occurs in each of the following pieces of code:
  2. x = y / 0
  3. x + y = z
  4. area = length + width

EXERCISE 3.6

  1. Describe how one can modify code so that the cause of a logic error can be discovered.
  2. The following program contains a logic error. Describe where to insert the appropriate debugging

statements to help locate the error:

importjava.util.Scanner;

publicclassAreaTriangle{

publicstaticvoidmain(String[]args){

doublebase,height,area;

Scannerreader=newScanner(System.in);

System.out.print(Enterthebaseofthetriangle:);

base=reader.nextDouble();

System.out.print(Entertheheightofthetriangle:);

height=reader.nextDouble();

area=base+height/2;

System.out.println(Theareais+area);

EXERCISE 3.7

  1. Write the code segments that would draw the following objects in the graphics context g:
  2. A filled rectangle with corner point (45, 20) and size 100 by 50
  3. A line segment with end points (20, 20) and (100, 100)
  4. A circle with center point (100, 100) and radius 50
  5. A triangle with vertices (100, 100), (50, 50), and (200, 200)
  6. Describe the design of a program that displays a filled blue rectangle on a red background.
  7. Explain how to compute the center point of a panel.
  8. List the three properties of a text font.

REVIEW Questions

WRITTEN QUESTIONS

Write a brief answer to the following questions.

  1. Write a pseudocode algorithm that determines the batting average of a baseball player.

(Hint: To compute a batting average, divide number of hits by number of at-bats. Batting

averages have three decimal places.)

  1. Give examples of an integer literal, a floating-point literal, and a string literal.
  2. Declare variables to represent a persons name, age, and hourly wage.
  3. Why must care be taken to order the operators in an arithmetic expression?
  4. Is it possible to assign a value of type int to a variable of type double? Why or why not?
  5. State which of the following are valid Java identifiers. For those that are not valid,

explain why.

  1. length
  2. import
  3. 6months
  4. hello-and-goodbye
  5. HERE_AND_THERE

FILL IN THE BLANK

Complete the following sentences by writing the correct word or words in the blanks provided.

  1. In mixed-mode arithmetic with operand types int and double, the result type is always

.

  1. A methods name, parameters, and return type are also known as its .
  2. The operation that joins two strings together is called .
  3. End-of-line comments begin with the symbol .
  4. A quotient results when the operator is used with two operands of type

.

Chapter 3 Syntax, Errors, and Debugging 1 0 3

PROJECTS

PROJECT 3-1

The surface area of a cube can be known if we know the length of an edge. Write a program

that takes the length of an edge (an integer) as input and prints the cubes surface area as output.

(Remember: analyze, design, implement, and test.)

PROJECT 3-2

Write a program that takes the radius of a sphere (a double) as input and outputs the spheres

diameter, circumference, surface area, and volume.

PROJECT 3-3

The kinetic energy of a moving object is given by the formula KE=(1/2)mv2, where m is the

objects mass and v is its velocity. Modify the program you created in Chapter 2, Project 2-5, so

that it prints the objects kinetic energy as well as its momentum.

PROJECT 3-4

An employees total weekly pay equals the hourly wage multiplied by the total number of regular

hours plus any overtime pay. Overtime pay equals the total overtime hours multiplied by

1.5 times the hourly wage. Write a program that takes as inputs the hourly wage, total regular

hours, and total overtime hours and displays an employees total weekly pay.

PROJECT 3-5

Modify the program you created in Project 3-4 so that it prompts the user for the regular and

overtime hours of each of five working days.

PROJECT 3-6

The Mller-Lyer illusion is caused by an image that consists of two parallel line segments.

One line segment looks like an arrow with two heads, and the other line segment looks like an

arrow with two tails. Although the line segments are of exactly the same length, they appear to

be unequal (see Figure 3-9). Write a graphics program that illustrates this illusion.

Write a graphics program that displays the coordinates of the center point of a panel in the

form (x, y). This information should be displayed at the panels center point and be automatically

updated when the panel is resized.

CRITICAL Thinking

During the summer, the registrars office must enter new data for incoming freshmen. Design

and implement a program that prompts the user for the following inputs:

Last name

First name

Class year (an integer)

Campus phone

After all the inputs are taken, the program should echo them as output.

 

 

Chapter 4:

Introduction to Control Statements

 

EXERCISE 4.1

  1. Translate the following statements to equivalent statements that use extended assignment operators:
  2. x = x * 2;
  3. y = y % 2;

Chapter 4 Introduction to Control Statements 1 0 7

EXERCISE 4.1 Continued

  1. Translate the following statements to equivalent statements that do not use the extended assignment

operators:

  1. x += 5;
  2. x *= x;

EXERCISE 4.2

  1. Assume that x has the value 3.6 and y has the value 4. State the value of the variable z after the following

statements:

  1. z = Math.sqrt(y);
  2. z = Math.round(x);
  3. z = Math.pow(y, 3);
  4. z = Math.round(Math.sqrt(x));
  5. Write code segments to print the following values in a terminal window:
  6. A random integer between 1 and 20, inclusive
  7. A random double between 1 and 10, inclusive

EXERCISE 4.3

  1. Why does Jill use a while statement in her instructions to Jack?
  2. Why does Jill use an if-else statement in her instructions to Jack? Write pseudocode control statements

that are similar in style to the farm example for the following situations:

  1. If a checker piece is red, then put it on a red square; otherwise, put it on a black square.
  2. If your shoes are muddy, then take them off and leave them outside the door.
  3. Pick up all the marbles on the floor and put them into a bag.

Chapter 4 Introduction to Control Statements 1 1 1

EXERCISE 4.3 Continued

  1. Describe in English what the following code segments do:

a.

if(xislargerthany){

temp=x;

x=y;

y=temp;

}else{

temp=y;

y=x;

x=temp;

}

b.

sum=0;

count=1;

readanintegerintototal;

while(countislessthanorequaltototal){

readanintegerintox;

sum=sum+Math.abs(x);

count++;

}

if(totalisgreaterthan0)

print(sum/total);

EXERCISE 4.4

  1. What type of expression must the condition of an if statement contain?
  2. Describe the role of the curly braces ({}) in an if statement.
  3. What is the difference between an if statement and an if-else statement?
  4. Assume that x is 5 and y is 10. Write the values of the following expressions:
  5. x <= 10
  6. x 2 != 0
  7. x > y
  8. Given the following minispecifications, write expressions involving relational operators:
  9. Determine if an input value x is greater than 0.
  10. Determine if a given number of seconds equals a minute.
  11. If a, b, and c are the lengths of the sides of a triangle and c is the largest side, determine if the

triangle is a right triangle. (Hint: Use the Pythagorean equation and round the operand before

comparing.)

  1. Write the outputs of the following code segments:

a.

intx=20,y=15,z;

if(x

z=10;

else

z=5;

System.out.println(z);

EXERCISE 4.4 Continued

b.

intx=2;

if(Math.round(Math.sqrt(x))==1)

System.out.println(Equal);

else

System.out.println(Notequal);

  1. Given the following minispecifications, write expressions involving if-else statements and output

statements:

  1. Print the larger of two numbers.
  2. Prompt the user for two whole numbers and input them. Then print the numbers in numeric order.

EXERCISE 4.5

  1. When does a while loop terminate execution?
  2. List the three components of a while loop.
  3. What happens if the condition of a while loop is false from the outset?
  4. Describe in English what the following code segments do:

a.

intexpo=1,limit=10;

while(expo<=limit){

System.out.println(expo++Math.pow(2,expo));

expo++;

}

b.

Scannerreader=newScanner(System.in);

intproduct=1;

System.out.print(Enterapositivenumberor999tohalt);

intx=reader.nextInt();

while(x!=-999){

product*=x;

System.out.print(Enterapositivenumberor999tohalt);

x=reader.nextInt();

}

  1. Write code segments to perform the following tasks:
  2. Print the squares and cubes of the first 10 positive integers.
  3. Print 10 random integers between 1 and 10 inclusive.
  4. Input names and ages of people until a persons age is 100.

EXERCISE 4.6

  1. Describe in English what the following code segments do:
  2. for(intexpo=1;expo<=limit;expo++)

System.out.println(expo++Math.pow(2,expo));

  1. intbase=2;

for(intcount=expo;count>1;count)

base=base*base;

  1. Write code segments that use for loops to perform the following tasks:
  2. Print the squares and cubes of the first 10 positive integers.
  3. Build a string consisting of the first 10 positive digits in descending order.
  4. Translate the following for loops to equivalent while loops:

a.

ScannerreadernewScanner(System.in);

for(inti=1;i<=5;i++){

System.out.print(Enteraninteger:);

intnumber=reader.nextInt();

System.out.println(Math.pow(number,2));

EXERCISE 4.6 Continued

b.

intbase=2;

for(intcount=expo;count>1;count-)

base=base*base;

EXERCISE 4.7

  1. Describe in English what the following code segments do:

a.

for(inti=1;i<=limit;i++)

if(i%2==0)

System.out.println(i);

b.

Randomgen=newRandom();

intmyNumber=gen.nextInt(10) + 1;

intx=0;

intyourNumber;

while(x==0){

System.out.println(Imguessinganumberbetween1and10.);

System.out.print(Whichnumberisit?);

yourNumber=reader.nextInt();

Chapter 4 Introduction to Control Statements 1 2 7

EXERCISE 4.7 Continued

if(myNumber==yourNumber){

System.out.println(Thatsit!);

break;

}elseSystem.out.println(Sorry,tryagain);

}

  1. Write code segments that use loops to perform the following tasks:
  2. Print the squares and cubes of the first 10 positive, odd integers.
  3. Build a string consisting of the first 10 positive, even digits in descending order.

EXERCISE 4.8

  1. Describe in English what the following code segment does:

Scannerreader=newScanner(newFile(myfile.txt));

  1. Write code segments that use loops to perform the following tasks:
  2. Read integers from a file and display them in the terminal window.
  3. Assume that there are an even number of integers in a file. Read them in pairs from the file and

display the larger value of each pair in the terminal window.

EXERCISE 4.9

  1. Describe the logic errors in the following loops:

a.

//Printtheoddnumbersbetween1andlimit,inclusive

for(inti=1;i

if(i%2==1)

System.out.println(i);

b.

//Printthefirsttenpositiveoddnumbers

intnumber=1;

while(number!=10)

System.out.println(number);

number+=2;

}

EXERCISE 4.10

  1. Write a code segment that uses an I/O dialog box to prompt the user for her name.
  2. Write a code segment that displays your name and address in a message box. Your name and

address should be formatted on separate lines by using the character.

  1. Explain why we need to use the methods Integer.parseInt and Double.parseDouble when

receiving numeric input from an I/O dialog box.

  1. Give an example of a situation where you would want a panel to set its preferred size, rather than

allow the size of the main window to determine that.

REVIEWQuestions

WRITTEN QUESTIONS

Write a brief answer to the following questions.

  1. Assume that the variables x and y contain the values 19 and 2, respectively. Indicate if the

Boolean expressions below are true, false, or syntactically incorrect.

  1. x <= y
  2. x * 2 > y
  3. x 1 == y * 9
  4. x < y < 25
  5. x * 2 != y
  6. For each of the following items, write a valid Java statement.
  7. Display greater if the value of variable x is greater than the value of variable y.

Otherwise, display less if the value of variable x is less than the value of variable y.

Otherwise, display equal.

  1. Add 10 to the value of x and display this value if the variable y is negative.
  2. Display the string A if x is greater than 90, B if x is greater than 80 and less than or

equal to 90, or C otherwise.

  1. Indicate whether or not each of the following loop headings is syntactically correct. If

incorrect, explain why.

  1. while (x > 0)
  2. while (y = 10)
  3. while x != 0
  4. Write a valid Java statement for each of the following items.
  5. Output the positive numbers from x up to y.
  6. Output the product of the squares of the numbers from x up to y.
  7. Output the numbers from y down to 0.
  8. Assume that the variables x and y contain integers. Write code to perform the following tasks.
  9. Output the largest value, using an if statement.
  10. Output the largest value, using the method Math.max.

PROJECTS

PROJECT 4-1

When you first learned to divide, you expressed answers using a quotient and a remainder

rather than a fraction or decimal quotient. For example, if you divided 9 by 2, you gave the

answer as 4r. 1. Write a program that takes two integers as inputs and displays their quotient and

remainder as outputs. Do not assume that the integers are entered in any order, but be sure to

divide the larger integer by the smaller integer.

PROJECT 4-2

Write a program that takes the lengths of three sides of a triangle as inputs. The program

should display whether or not the triangle is a right triangle.

PROJECT 4-3

A 2-minute telephone call to Lexington, Virginia, costs $1.15. Each additional minute costs

$0.50. Write a program that takes the total length of a call in minutes as input and calculates and

displays the cost.

Chapter 4 Introduction to Control Statements 1 4 7

PROJECT 4-4

Run the Factorial program of Section 4.5 with inputs of 5, 10, and 20. Notice that the

number for the last output is large but negative. Place an output statement in the loop so that you

can view the value of count and number on each pass. Can you explain what the problem is?

Now change the type of product from int to long, recompile the program, and run it again

with the same inputs. Explain what happens. How large does the input have to be before you

encounter the same problem again?

PROJECT 4-5

The German mathematician Gottfried Leibniz developed the following method to approximate

the value of :

/4 = 1 13 + 15 17 + . . .

Write a program that allows the user to specify the number of iterations used in this approximation

and displays the resulting value.

PROJECT 4-6

A local biologist needs a program to predict population growth. The inputs would be the initial

number of organisms, the rate of growth (a real number greater than 0), the number of hours

it takes to achieve this rate, and a number of hours during which the population grows. For

example, one might start with a population of 500 organisms, a growth rate of 2, and a growth

period to achieve this rate of 6 hours. Assuming that none of the organisms die, this would imply

that this population would double in size every 6 hours. Thus, after allowing 6 hours for growth,

we would have 1000 organisms, and after 12 hours, we would have 2000 organisms. Write a

program that takes these inputs and displays a prediction of the total population.

PROJECT 4-7

Computers use the binary system, which is based on powers of 2. Write a program that displays

the positive powers of 2. When the user enters the exponent at a prompt, the program displays

2 to that power. The program halts when the user enters 1.

PROJECT 4-8

Modify the program of Project 4-7 so that the user can specify the base (2 or higher) as well.

The first line of the output should display which base was entered.

PROJECT 4-9

Modify the program of Project 4-8 so that it processes a file of inputs. Each line of the file

contains a base and an exponent. The program should read the data from each line, compute the

result, and display each set of inputs and their result on an output line in the terminal windo

PROJECT 4-10

Teachers in most school districts are paid on a schedule that provides a salary based on their

number of years of teaching experience. For example, a beginning teacher in the Bellingham

School District might be paid $30,000 the first year. For each year of experience after this up to

10 years, a 2 percent increase over the preceding value is received. Write a program that displays

a salary schedule for teachers in a school district. The inputs are the starting salary, the percentage

increase, and the number of years in the schedule. Each row in the schedule should contain

the year number and the salary for that year.

PROJECT 4-11

A checkerboard consists of an 8-by-8 grid of black and red squares in which no two squares

of the same color are adjacent. Write a graphics program that displays a checkerboard.

PROJECT 4-12

Modify the program of Project 4-11 so that it prompts the user for the number of rows and

columns of the board before displaying them. Use I/O dialog boxes to accept the inputs.

PROJECT 4-13

An interesting optical illusion is caused by a phenomenon known as induced contrast. This

illusion occurs when two images of the same shade are placed on backgrounds of sharply contrasting

shades, as shown in Figure 4-7. One image appears darker than the other, even though

they are exactly the same shade. Write a graphics program that generates such an illusion. (Hint:

Use two panels that draw the same shape.)

CRITICALThinking

Do the mathematical analysis needed to show that the Lucky Sevens game is not so lucky for

the gambler. (Hint: The answer involves comparing the number of possible combinations of all

totals and the number of possible combinations of 7.)

 

 

Chapter 5:

Using Classes and Objects in Media Computting

 

EXERCISE 5.1

  1. Describe the difference between Cartesian coordinates and screen coordinates.

 

EXERCISES 5.2

  1. What information is contained in an interface?
  2. Write a Java code segment that creates a blank image and converts its pixels to green. Your code

should use an enhanced for loop.

  1. Write a Java code segment that draws a blue border around the edges of an image. You may overwrite

the pixels on the edges.

EXERCISES 5.3

  1. Describe how a row-major traversal visits every position in a two-dimensional grid.
  2. How would a column-major traversal of a grid work? Write a code segment that prints the positions

visited by a column-major traversal of a 2 by 3 grid.

  1. Explain why you would use the clone method with a given object.
  2. Why does the edge-detection algorithm need to create a new image?
  3. Write a Java code segment that draws a blue border around the edges of an image. Unlike the code

in an earlier exercise, this code should not overwrite the edges of the original image, but instead create

a new image with the contents of the original image enclosed in the border.

  1. Write a Java code segment that creates a grayscale copy of an image. The original image should be

unchanged.

  1. Write a Java code segment that creates a black-and-white copy of an image. The original image

should be unchanged.

EXERCISES 5.5

  1. Write a Java code segment that prints the maximum and minimum values of the samples in a

sound clip.

  1. Write a Java code segment that prints the number of seconds required to play a sound clip.

REVIEW Questions

MULTIPLE CHOICE QUESTIONS

Select the correct answer from the list of possibilities.

  1. The interface of a class is the set of all its .
  2. objects b. attributes
  3. methods

Chapter 5 Using Classes and Objects in Media Computing 1 7 5

  1. A mutator method .
  2. examines the contents of an object b. changes the contents of an object
  3. creates a new object
  4. Instantiation is a process that .
  5. compares two objects for equality b. builds a string representation of an object
  6. creates a new object of a given class
  7. The toStringmethod .
  8. creates a new object b. copies an existing object
  9. returns a string representation of an object
  10. The clonemethod .
  11. creates a new object b. copies an existing object
  12. returns a string representation of an object
  13. The origin (0, 0) in a screen coordinate system is at .
  14. the center of a window b. the upper-left corner of a window
  15. A row-major traversal of a two-dimensional grid visits all of the positions in a .
  16. row before moving to the next row b. column before moving to the next column
  17. In the RGB system, where each color contains three components with 256 possible values

each, grayscale colors contain .

  1. RGB components that are equal b. RGB components that are either 0 or 1
  2. The integer values in digital sound samples represent .
  3. amplitude b. pitch
  4. The process whereby analog information is converted to digital information is called

.

  1. recording b. sampling
  2. filtering d. compressing

PROJECTS

In the projects that follow, you are asked to develop Java programs that implement algorithms

for transforming images and sound clips. The structure of these programs should be similar

to those of the examples presented in this chapter. In the case of the image-processing

programs, be sure to display the images before and after each transformation.

PROJECT 5-1

An algorithm to posterize a given image works like the algorithm to convert an image to

black and white, but uses two given color values instead. Write a program that prompts the user

  1. for an image filename. The program should posterize the image with two random colors.

 

The algorithm to convert a color image to gray scale averages each RGB value. Although this

method is simple, it does not reflect the manner in which the different color components affect

human perception. The human eye is actually more sensitive to green and red than it is to blue. As

a result, the blue component appears darker than the other two components. A scheme that combines

the three components needs to take these differences in luminance into account. A more

accurate method would weight green more than red and red more than blue. Therefore, to obtain

the new RGB values, instead of adding up the color values and dividing by three, you should multiply

each one by a weight factor and add the results. Psychologists have determined that the relative

luminance proportions of green, red, and blue are .587, .299, and .114, respectively. Note that

these values add up to 1. Write a program that uses this more sophisticated method to convert a

color image to gray scale and compare its results with those of the other method.

PROJECT 5-3

Inverting a grayscale image makes it look like a photographic negative. To do this, you reset each

RGB component to 255 minus that component. Write a program that inverts grayscale images.

PROJECT 5-4

Old-fashioned photographs from the nineteenth century are not quite black and white and

not quite color, but seem to have shades of gray, brown, and blue. This effect is known as sepia.

Write a program that converts a color image to sepia. This program should first convert the color

image to gray scale. A code segment for transforming a grayscale value to achieve a sepia effect

follows. Note that the value for green does not change.

if (red < 63){

red = (int)(red * 1.1);

blue = (int)(blue * 0.9);

}else if (red < 192){

red = (int)(red * 1.15);

blue = (int)(blue * 0.85);

}else{

red = Math.min(int(red * 1.08), 255);

blue = (int)(blue * 0.93);

}

PROJECT 5-5

Darkening an image requires adjusting all of its pixels toward black as a limit, whereas

brightening an image requires adjusting them toward white as a limit. Because black is RGB (0,

0, 0) and white is RGB (255, 255, 255), adjusting the three RGB values of each pixel by the same

amount in either direction will have the desired effect. Of course, the algorithms have to avoid

exceeding either limit during the adjustments.

Brightening and darkening are actually special cases of a process known as color filtering. A

color filter is any RGB triple applied to an entire image. The filtering algorithm adjusts each pixel

by the amounts specified in the triple. For example, you can increase the amount of red in an

image by applying a color filter with a positive red value and green and blue values of 0. The filter

(20, 0, 0) would make an images overall color slightly redder. Alternatively, you can reduce

Chapter 5 Using Classes and Objects in Media Computing 1 7 7

the amount of red by applying a color filter with a negative red value. Once again, the algorithms

have to avoid exceeding the limits on the RGB values.

Write a program that applies a color filter to an image. The inputs are an image filename and

the RGB values of the filter.

PROJECT 5-6

The edge-detection program developed in this chapter produces a black-and-white image.

Think of a similar way to transform color values so that the new image is still in its original colors

but the outlines within it are merely sharpened. Then, write a new program that performs this

operation. The program expects an image filename and two integers as inputs. One integer

should represent the degree to which the image should be sharpened. The other integer should

represent the threshold used to detect edges. (Hint: A pixel can be darkened or brightened by

making its RGB values smaller or larger.)

PROJECT 5-7

Occasionally, an image appears to contain rough, jagged edges. This condition, known as pixilation,

can be mitigated by blurring the images problem areas. Blurring makes these areas appear

softer, but at the cost of losing some definition. Write a program to blur an entire image. This program

should reset each pixels color to the average of the colors of the four pixels that surround it.

The program should produce a copy of the input image with blurring. The program should begin

its traversal of the grid with position (1, 1) and end with position (width 2, height 2). Although

this means that the program does not transform the pixels on the images outer edges, you do not

have to check for the grids boundaries when you obtain information from a pixels neighbors.

PROJECT 5-8

Write a program to reduce the size of an image by a given factor. The program should expect

an image filename and a positive integer shrinkage factor as inputs. A shrinkage factor of 2 tells

Java to shrink the image to one-half of its original dimensions, a factor of 3 tells Java to shrink

the image to one-third of its original dimensions, and so forth. The program uses the shrinkage

factor to compute the size of the new image and then creates it. Because a one-to-one mapping of

grid positions in the two images is not possible, separate variables are used to track the positions

of the pixels in the original image and the new image. The loop traverses the larger image (the

original) and skips positions by incrementing its coordinates by the shrinkage factor. The new

images coordinates are incremented by 1, as usual. The loop continuation conditions are also

offset by the shrinkage factor to avoid range errors.

PROJECT 5-9

To enlarge an image, you must fill in new rows and columns with color information based on

the colors of neighboring positions in the original image. Write a program that expects an image

filename and an integer factor as arguments. The program builds and displays a new image that

represents the expansion of the original image by the factor. (Hint: Copy each row of pixels in the

original image to one or more rows in the new image. To copy a row, use two index variables,

one that starts on the left of the row and one that starts on the right. These two indexes converge

to the middle position in a row, with the left index increasing and the right index decreasing. This

will allow you to copy each pixel to one or more positions of a row in the new image.)

PROJECT 5-10

An image is rotated by copying color values from their original positions to the appropriate

positions in a new image. For example, to rotate an image by 180 degrees, you swap the pixels at

positions (0, 0) and (width 1, height 1), and so forth. Care must be taken in creating a new

image, whose dimensions might differ from those of the original. Write a program that rotates an

image by 90 degrees, counterclockwise.

PROJECT 5-11

Modify the sample program that adjusts the volume of a sound clip so that it avoids exceeding

the limits on the size of a sample. You should use the constants Sample.MIN_VALUE and

Sample.MAX_VALUE in your solution.

PROJECT 5-12

Write a program that splices two sound clips. The program should expect the filenames of

two sound clips as inputs. It should then create a new clip into which the samples of the two

input clips are copied. Be sure to allow enough room in the new clip for the samples of the two

inputs, as well as one-tenth of a second of blank sound between them. The program should draw

the new clip, which will allow the user to play it or save it to a file.

PROJECT 5-13

Write a program that composes two sound clips. The program should expect the filenames of

two sound clips as inputs. It should create a new clip in which the samples of the two input clips

are composed (that is, they will play simultaneously). The program should then draw the new

clip, which will allow the user to play it or save it to a file.

PROJECT 5-14

Write a program that introduces echo into a sound clip. The program should expect three

inputs. The first is the time delay for the echo and the other two are the filenames of two sound

clips (the original clip to be loaded and the new clip to be created and saved). The program

should create a new clip and

Write a review

Your Name:


Your Review: Note: HTML is not translated!

Rating: Bad           Good

Enter the code in the box below:



 

Once the order is placed, the order will be delivered to your email less than 24 hours, mostly within 4 hours. 

If you have questions, you can contact us here