<< Solution Manual For Principles Of Managerial Finance 13Th Edition By Lawrence J. Gitman | Sociology The Essentials 8th Edition By Andersen-Test Bank >> |
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
REVIEW Questions
WRITTEN QUESTIONS
Write a brief answer to each of the following questions.
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.
life cycle.
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
EXERCISE 2.2
EXERCISE 2.4
window.
EXERCISE 2.5
EXERCISE 2.6
of each.
EXERCISE 2.7
You may assume that the panels content pane is named pane.
REVIEWQuestions
WRITTEN QUESTIONS
Write a brief answer to each of the following questions.
FILL IN THE BLANK
Complete the following sentences by writing the correct word or words in the blanks provided.
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
EXERCISE 3.2 Continued
EXERCISE 3.2 Continued
Which of the types listed in this subsection are not included?
EXERCISE 3.2 Continued
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
expressions:
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
statements, state which are valid and which produce syntax errors:
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
of the following expressions:
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
following expressions:
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
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
EXERCISE 3.2 Continued
EXERCISE 3.3
a line of text from the keyboard.
EXERCISE 3.4
EXERCISE 3.5 Continued
EXERCISE 3.5 Continued
EXERCISE 3.6
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
REVIEW Questions
WRITTEN QUESTIONS
Write a brief answer to the following questions.
(Hint: To compute a batting average, divide number of hits by number of at-bats. Batting
averages have three decimal places.)
explain why.
FILL IN THE BLANK
Complete the following sentences by writing the correct word or words in the blanks provided.
.
.
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
Chapter 4 Introduction to Control Statements 1 0 7
EXERCISE 4.1 Continued
operators:
EXERCISE 4.2
statements:
EXERCISE 4.3
that are similar in style to the farm example for the following situations:
Chapter 4 Introduction to Control Statements 1 1 1
EXERCISE 4.3 Continued
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
triangle is a right triangle. (Hint: Use the Pythagorean equation and round the operand before
comparing.)
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); statements: EXERCISE 4.5 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(); } EXERCISE 4.6 System.out.println(expo++Math.pow(2,expo)); for(intcount=expo;count>1;count) base=base*base; 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 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); } EXERCISE 4.8 Scannerreader=newScanner(newFile(myfile.txt)); display the larger value of each pair in the terminal window. EXERCISE 4.9 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 address should be formatted on separate lines by using the
character. receiving numeric input from an I/O dialog box. allow the size of the main window to determine that. REVIEWQuestions WRITTEN QUESTIONS Write a brief answer to the following questions. Boolean expressions below are true, false, or syntactically incorrect. Otherwise, display less if the value of variable x is less than the value of variable y. Otherwise, display equal. equal to 90, or C otherwise. incorrect, explain why. 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 EXERCISES 5.2 should use an enhanced for loop. the pixels on the edges. EXERCISES 5.3 visited by a column-major traversal of a 2 by 3 grid. 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. unchanged. should be unchanged. EXERCISES 5.5 sound clip. REVIEW Questions MULTIPLE CHOICE QUESTIONS Select the correct answer from the list of possibilities. Chapter 5 Using Classes and Objects in Media Computing 1 7 5 each, grayscale colors contain . . 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 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
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