37
Exercises: 1. Write a fragment of code that will read words from the keyboard until the word done is entered. For each word except done, report whether its first character is equal to its last character. For the required loop, use a a. while statement b. do-while statement Solution: Scanner reader = new Scanner(System.in); String word = ""; System.out.println("Please enter words ending with done."); word = reader.next(); while(!word.equals("done")){ if(word.charAt(0) == word.charAt(word.length()-1)){ System.out.println("The word " + word + " has first and last characters that are the same."); } word = reader.next(); } System.out.println("Please enter words ending with done."); boolean finished = false; do{ word = reader.next(); if(word.equals("done")) finished = true; else if(word.charAt(0) == word.charAt(word.length()-1)){ System.out.println("The word " + word + " has first and last characters that are the same."); } } while (!finished);

Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

Exercises:

1. Write a fragment of code that will read words from the keyboard until the word done is entered. For each word except done, report whether its first character is equal to its last character. For the required loop, use aa. while statementb. do-while statement

Solution: Scanner reader = new Scanner(System.in); String word = ""; System.out.println("Please enter words ending with done."); word = reader.next(); while(!word.equals("done")){ if(word.charAt(0) == word.charAt(word.length()-1)){ System.out.println("The word " + word

+ " has first and last characters that are the same.");

} word = reader.next(); } System.out.println("Please enter words ending with done."); boolean finished = false; do{ word = reader.next(); if(word.equals("done")) finished = true; else if(word.charAt(0) == word.charAt(word.length()-1)){ System.out.println("The word " + word

+ " has first and last characters that are the same.");

} } while (!finished);

This code is in Fragments.java.

Page 2: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

2. Develop an algorithm for computing the month-by-month balance in your savings account. You can make one transaction—a deposit or a withdrawal—each month. Interest is added to the account at the beginning of each month. The monthly interest rate is the yearly percentage rate divided by 12.

Solution:

1. For month goes from 1 to 121.1. Compute the monthly interest1.2. Compute the interest and add to the balance1.3. Ask if the user is making a deposit or withdrawal.1.4. Get the amount from the user1.5. If making a deposit

1.5.1. Add the amount to the balance1.6. Else

1.6.1. Subtract the amount from the balance1.7. Display the current balance

Page 3: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

3. Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code, the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond with 2 and 7.Allow the user to guess a fixed number of times.

Solution:

1. Generate a secret code2. For guess is 1 to max

2.1. Get the users guess for the 5 digit code2.2. Let correct be zero2.3. Let sum be zero2.4. For each digit

2.4.1. If the digit in the guess matches the users guess2.4.1.1. Add 1 to correct2.4.1.2. Add the value of the digit to sum

2.5. If correct is 52.5.1. Congratulate the user on guessing the code2.5.2. Exit the program

2.6. Else2.6.1. Display correct and sum

2.7. Ask if the user is making a deposit or withdrawal.3. Display a message telling the user they did not guess the code within the

maximum number of allowed guesses.

Page 4: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

4. Write a fragment of code that will compute the sum of the first n positive odd integers. For example, if n is 5, you should compute 1 + 3 + 5 + 7 + 9.

Solution:

int sum = 0;int odd = 1;for(int i=0; i<n; i++){

sum += odd;odd += 2;

}

System.out.println("The sum of the first " + n + " odd numbers is " + sum);

This code is in Fragments.java.

Page 5: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

5. Convert the following code so that it uses nested while statements instead of for statements:int s = 0;int t = 1;for (int i = 0; i < 10; i++){s = s + i;for (int j = i; j > 0; j--){t = t * (j - i);}s = s * t;System.out.println(“T is “ + t);}System.out.println(“S is “ + s);

Solution:

int s = 0;int t = 1;int i = 0;while(i<10){

s = s + i; int j = i; while(j>0){ t = t * (j - i); j--; } s = s * t; System.out.println("T is " + t); i++;

}System.out.println("S is " + s);

This code is in Fragments.java.

Page 6: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

6. Write a for statement to compute the sum 1 + 22 + 32 + 42 + 52 + ... + n2.

Solution:

sum = 0;for( i=1; i<=n; i++){

sum += i*i;}System.out.println("The sum is " + sum);

This code is in Fragments.java.

7. (Optional) Repeat the previous question, but use the comma operator and omit the for statement’s body.

Solution:

for( sum=0, i=1; i<=n; sum += i*i, i++){}System.out.println("The sum is " + sum);

This code is in Fragments.java.

Page 7: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

11. Suppose we attend a party. To be sociable, we will shake hands with everyone else. Write a fragment of code using a for statement that will compute the total number of handshakes that occur. (Hint: Upon arrival, each person shakes hands with everyone that is already there. Use the loop to find the total number of handshakes as each person arrives.)

Solution:

int numberAttending = 8;int handShakes = 0;for( int person=1; person <= numberAttending; person++){ handShakes += (person - 1); // When person k arrives, they will //shake hands with the k-1 people already there}System.out.println("The sum is " + sum);

This code is in Fragments.java.

Page 8: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

12. Define an enumeration for each of the months in the year. Use a for-each statement to display each month.

Solution:

enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}for (Month nextMonth : Month.values()) System.out.print(nextMonth + " ");System.out.println();

This code is in Fragments.java.

13. Write a fragment of code that computes the final score of a baseball game. Use a loop to read the number of runs scored by both teams during each of nine innings. Display the final score afterwards.

Solution:

int innings = 9; int team1Total = 0; int team2Total = 0; //Scanner reader = new Scanner(System.in);

for( int inning=1; inning <= innings; inning++){ System.out.println("How many runs were scored in inning " + inning + " by each team?"); team1Total = team1Total + reader.nextInt(); team2Total = team2Total + reader.nextInt(); } System.out.println("The first team scored: " + team1Total + " and the second team scored: " + team2Total);

This code is in Fragments.java.

Page 9: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

14. Suppose that you work for a beverage company. The company wants to know the optimal cost for a cylindrical container that holds a specified volume. Write a fragment of code that uses an ask-before-iterating loop. During each iteration of the loop, your code will ask the user to enter the volume and the radius of the cylinder. Compute and display the height and cost of the container. Use the following formulas, where V is the volume, r is the radius, h is the height, and C is the cost.

Solution: double volume = 0.0; double height = 0.0; double radius = 0.0; double cost = 0.0; String answer; //Scanner reader = new Scanner(System.in); do { System.out.println("Enter the volume and radius " + "of the cylinder "); volume = reader.nextDouble(); radius = reader.nextDouble(); height = volume / (Math.PI * radius * radius); cost = 2 * Math.PI * radius *(radius + height); System.out.println("The height required is: " + height + " and the cost is " + cost); System.out.println("Do you want to compute the " + "cost for a different volume & height?"); System.out.println("Enter yes or no."); answer = reader.next(); } while (answer.equalsIgnoreCase("yes"));

This code is in Fragments.java.

Page 10: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter
Page 11: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

15. Suppose that we want to compute the geometric mean of a list of positive values. To compute the geometric mean of k values, multiply them all together and thenCcompute the kth root of the value. For example, the geometric mean of 2, 5, and 7 is . Use a loop with a sentinel value to allow a user to enter an arbitrary number of values. Compute and display the geometric mean of all the values, excluding the sentinel. (Hint: Math.pow(x, 1.0 / k) will compute the kth root of x.)

Solution:

int count = 0; double data = 0.0; double product = 1.0; //Scanner reader = new Scanner(System.in); System.out.println("Enter data values for which" + " to compute the geometric mean."); System.out.println("Enter a negative number after"); System.out.println("you have entered all the data values."); data = reader.nextDouble(); while (data >= 0) { product = product * data; count++; data = reader.nextDouble(); } System.out.println("The geometric mean is " + Math.pow(product, 1.0/count));

This code is in Fragments.java.

Page 12: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

16. Imagine a program that compresses files by 80 percent and stores them on storage media. Before the compressed file is stored, it must be divided into blocks of 512 bytes each. Develop an algorithm for this program that first reads the number of blocks available on the storage media. Then, in a loop, read the uncompressed size of a file and determine whether the compressed file will fit in the space left on the storage media. If so, the program should compress and save the file. It continues until it encounters a file that will exceed the available space on the media. For example, suppose the media can hold 1000 blocks. A file of size 1100 bytes will compress to size 880 and require 2 blocks. The available space is now 998blocks. A file of size 20,000 bytes will compress to size 16,000 and require 32 blocks. The available space is now 966.

Solution:

1. Get the number of free blocks and assign it to the variable free2. Let haveSpace be true3. While haveSpace

3.1. Get size of the file in bytes3.2. Compute the compressed size of the file in bytes3.3. Determine the number of blocks needed for the file3.4. If the number of blocks needed is less than the free space

3.4.1. Reduce the number of free blocks3.5. Else

3.5.1. Let haveSpace be false3.5.2. guess is 1 to max

17. Create an applet that draws a pattern of circles whose centers are evenly spaced along a horizontal line. Use six constants to control the pattern: the number of circles to draw, the diameter of the first circle, the x- and y-coordinates of the center of the first circle, the distance between adjacent centers, and the change in the diameter of each subsequent circle.

Page 13: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

Solution:

See the code in MultipleCircles.java.

Page 14: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

18. What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?int product = 1;int max = 20;for (int i = 0; i <= max; i++)product = product * i;System.out.println(“The product is “ + product);

Solution:

The product displayed is 0. It is likely that the programmer wanted to compute the product of the first 20 integer values. Change the for loop to be:

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

19. What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?int sum = 0;int product = 1;int max = 20;for (int i = 1; i <= max; i++)sum = sum + i;product = product * i;System.out.println(“The sum is “ + sum +“ and the product is “ + product);

Solution:

The sum is 210 and the product is 21.0. It is likely that the programmer wanted to compute the product of the first 20 integer values, only the statement

sum = sum + i; is inside the body of the for loop. Change the for loop to be:

for (int i = 1; i <= max; i++){sum = sum + i;product = product * i;

}

Page 15: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter
Page 16: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

Projects:

1. Repeat Programming Project 4 of Chapter 3, but use a loop that reads and processes sentences until the user says to end the program.

Notes:

This project is an extension of a project from the previous chapter to use looping.

References:

Project 3.4

Solution:

See the code in AskOrTellMe.java.

2. Write a program that implements your algorithm from Exercise 2.

Notes:

This project uses a loop to simulate a simplified checking account. It is strongly recommended that students develop an algorithm first (Exercise 2) to instill good design practices. This gives them a chance to see how well their design worked.

References:

Exercise 4.2

Solution:

See the code in MonthByMonth.java.

Page 17: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

3. Repeat Programming Project 5 of Chapter 3, but use a loop so the user can convert other temperatures. If the user enters a letter other than C or F—in either uppercase or lowercase—after a temperature, print an error message and ask the user to reenter a valid selection. Do not ask the user to reenter the numeric portion of the temperature again, however. After each conversion, ask the user to type Q or q to quit or to press any other key to repeat the loop and perform another conversion.

Notes:

This project uses loops to further enhance the program TemperatureConversionSelction developed in Chapter 3 (which enhanced FtoC developed in Chapter 2). A common error is to write the while control expression as an OR instead of an AND, so the loop does not end when either ‘Q’ or ‘q’ is entered. With an OR expression one or both sides of the expression will always be true (if ‘Q’ is entered, the variable quit is not equal to ‘q’, and vice versa); quit must be both not equal to ‘Q’ and not equal to ‘q’ to enter the loop.

References:

Project 2.6, Project 3.5

Solution:

See the code in TemperatureConversion.java.

Page 18: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

5. Write a program to read a list of nonnegative integers and to display the largest integer, the smallest integer, and the average of all the integers. The user indicates the end of the input by entering a negative sentinel value that is not used in finding the largest, smallest, and average values. The average should be a value of type double, so that it is computed with a fractional part.

Notes:

The solution for this project includes a default case to print a message if no positive integers are entered.

Solution:

See the code in LargeSmallAverage.java.

Page 19: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

6. Write a program to read a list of exam scores given as integer percentages in the range 0 to 100. Display the total number of grades and the number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, and 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.) For example, if the input is

98 87 86 85 85 78 73 72 72 72 70 66 63 50 −1

the output would be

Total number of grades = 14Number of A’s = 1Number of B’s = 4Number of C’s = 6Number of D’s = 2Number of F’s = 1

Notes:

This project requires both a sentinel controlled loop, multi-way selection, and running sums that need to be initialized to zero to guarantee correct results.

Solution:

See the code in NumberOfGrades.java.

Page 20: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

7. Combine the programs from Programming Projects 5 and 6 to read integer exam scores in the range 0 to 100 and to display the following statistics:Total number of scoresTotal number of each letter gradePercentage of total for each letter gradeRange of scores: lowest and highestAverage scoreAs before, enter a negative score as a sentinel value to end the data input and display the statistics.

Notes:

This project combines parts of the previous two projects. There is the potential for incorrect results due to integer division truncation, so a cast to float is used for the percent and average calculations. The solution in this manual also does a check to see if no scores have been entered, and, if so, displays a special message rather than the statistics.

References:

Project 4.5, Project 4.6Solution:

See the code in ExamStatistics.java.

Page 21: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

10. Write a program that reads a bank account balance and an interest rate and displays the value of the account in ten years. The output should show the value of the account for three different methods of compounding interest: annually, monthly, and daily. When compounded annually, the interest is added once per year at the end of the year. When compounded monthly, the interest is added 12 times per year. When computed daily, the interest is added 365 times per year. You do not have to worry about leap years; assume that all years have 365 days. For annual interest, you can assume that the interest is posted exactly one year from the date of deposit. In other words, you do not have to worry about interest being postedon a specific day of the year, such as December 31. Similarly, you can assume that monthly interest is posted exactly one month after it is deposited. Since the account earns interest on the interest, it should have a higher balance when interest is posted more frequently. Be sure to adjust the interest rate for the time period of the interest. If the rate is 5 percent, you use 5/12 percent when posting monthly interest and 5/365 percent when posting daily interest. Perform this calculation using a loop that adds in the interest for each time period, that is, do not use some sort of algebraic formula. Your program should have an outer loop that allows the user to repeat this calculation for a new balance and interest rate. The calculation is repeated until the user asks to end the program.

Notes:

This project is a bank account problem, so it requires the same consideration about money calculations as the mortgage problem in Chapter 2. The round function in Java will not be introduced until later, so a discussion of the special problems associated with money calculations may be postponed until then. One solution in this manual, BankAccount.java, takes a simplistic approach, uses floating point values and does not round to the nearest penny. For contrast, a second program, BankAccount2.java, which deals with the rounding problem (without using Java’s round function), is also provided.

Solution:

Page 22: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

See the code in BankAccount.java and BankAccount2.java.

Page 23: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

11. Modify Programming Project 10 from Chapter 2 to check the validity of input data. Valid input is no less than 25 cents, no more than 100 cents, and an integer multiple of 5 cents. Compute the change only if a valid price is entered. Otherwise, print separate error messages for any of the following invalid inputs: a price under 25 cents, a price that is not an integer multiple of 5, and a price that is more than a dollar.

Notes:

This project is a simple modification of Project 10 from Chapter 2. Three if statements are added to detect invalid input: less than 25 cents, more than a dollar, and not a multiple of 5 cents.

References:

Project 2.10

Solution:

See the code in VendingChangeImproved.java.

Page 24: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

13. Write a program that asks the user to enter the size of a triangle (an integer from 1 to 50). Display the triangle by writing lines of asterisks. The first line will have one asterisk, the next two, and so on, with each line having one more asterisk than the previous line, up to the number entered by the user. On the next line write one fewer asterisk and continue by decreasing the number of asterisks by 1 for each successive line until only one asterisk is displayed. Hint: Use nested for loops; the outside loop controls the number of lines to write, and the inside loop controls the number of asterisks to display on a line. For example, if the user enters 3, the output would be*********

Notes:

This project includes input checking so it will not print any lines with asterisks if the user enters a number less than 1 or greater than 50. If a valid number is entered, two pairs of nested for-loops are used to print the triangle of asterisks. The first nested pair prints the lines with an increasing number of asterisks, starting with one and increasing by one per line up to a maximum of the number entered by the user. The second nested pair of for-loops prints the lines with a decreasing number of asterisks, starting with (number –1) down to 1. The outside loops count through the lines printed and the inside loops count through the number of asterisks printed on the line. The number of asterisks to print on any line is its line number set by the outside loop.

Solution:

See the code in TriangleOfAsterisks.java.

Page 25: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

14. Write a program that simulates a bouncing ball by computing its height in feet at each second as time passes on a simulated clock. At time zero, the ball begins at height zero and has an initial velocity supplied by the user. (An initial velocity of at least 100 feet per second is a good choice.) After each second, change the height by adding the current velocity; then subtract 32 from the velocity. If the new height is less than zero, multiply both the height and the velocity by -0.5 to simulate the bounce. Stop at the fifth bounce. The output from your program should have the following form:Enter the initial velocity of the ball: 100Time: 0 Height: 0.0Time: 1 Height: 100.0Time: 2 Height: 168.0Time: 3 Height: 204.0Time: 4 Height: 208.0Time: 5 Height: 180.0Time: 6 Height: 120.0Time: 7 Height: 28.0Bounce!Time: 8 Height: 48.0

Notes:

This project is a numerical simulation of a bouncing ball. The simulation of the bounce is not particularly realistic, but it avoids dealing with issues of determining exactly when the ball hits the surface. The quality of the simulation is sensitive to the combination of the input parameters.

Solution:

See the code in Bounce.java.

15. You have three identical prizes to give away and a pool of 10 finalists. The finalists are assigned numbers from 1 to 10. Write a program to randomly select the numbers of 3 finalists to receive a prize. Make sure not to pick the same

Page 26: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

number twice. For example, picking finalists 3, 6, 2 would be valid but picking 3, 3, 11 would be invalid because finalist number 3 is listed twice and 11 is not a valid finalist number. Random number generation is discussed in Chapter 6, but for this problem you can insert the following line of code to generate a random number between 1 and 10:

int num = (int) (Math.random() * 10) +1;

Notes:

This project uses random numbers in a loop. You might wish to introduce the Random class instead of Math.random().

Solution:

See the code in RandomWinners.java.

16. Suppose we can buy a chocolate bar from the vending machine for $1 each. Inside every chocolate bar is a coupon. We can redeem 6 coupons for one chocolate bar from the machine. This means that once you have started buying chocolate bars from the machine, you always have some coupons. We would like to know how many chocolate bars can be eaten if we start with N dollars and always redeem coupons if we have enough for an additional chocolate bar.

For example, with 6 dollars we could consume 7 chocolate bars after purchasing 6 bars giving us 6 coupons and then redeeming the 6 coupons for one bar. This would leave us with one extra coupon. For 11 dollars, we could have consumed 13 chocolate bars and still have one coupon left. For 12 dollars, we could have consumed 14 chocolate bars and have two coupons left.

Page 27: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

Write a program that inputs a value for N and outputs how many chocolate bars we can eat and how many coupons we would have leftover. Use a loop that continues to redeem coupons as long as there are enough to get at least one chocolate bar.

Notes:

Students often attempt this problem by trying to find a simple formula instead of simulating the process in a loop. This also makes a good problem to re-do later after covering recursion.

Solution:

See the code in ChocolateCoupons.java.

Page 28: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

17. Repeat the previous project, but write the program as an applet. Use a constant for the initial velocity of the ball. Draw a circle for the position of the ball at each second. The y-coordinate should be proportional to the height of the ball, and the xcoordinate should change by a small constant amount.

Notes:

This applet shows a graphical representation of the previous project. If the time increment used is too large, the resulting picture may look chaotic and not at all like a trajectory.

References:

Project 4.14

Solution:

See the code in BounceApplet.java. If the scale factor and initial velocity are chosen badly, your picture may not look very much like a bouncing ball. Instead, it may look chaotic. For example, try initial velocity of 100 and scale of 2.

19. Create an applet that draws a pattern of evenly spaced circles. Use four constants to control the pattern: the number of circles to draw, the radius of the first circle, the change in the radius of each subsequent circle, and the change in the x-coordinate of the circle.

Notes:

This applet uses looping to control drawing a number of circles. Changing the parameters results in interesting patterns.

Solution:

See the code in LineCircles.java.

Page 29: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

20. (Challenge) Repeat the previous project, but position the centers of the circles on a spiral. The center of each circle will depend on both an angle and a distance from the origin. A constant change in both the angle and the distance will result in a spiral pattern.

Notes:

This applet is an extension of the previous applet to draw the circles on a spiral. Knowledge of converting polar coordinates to Cartesian coordinates is helpful.

References:

Project 4.17

Solution:

See the code in SpiralCircles.java.

Page 30: Exercises: - Southern Illinois University Edwardsvillesteklei/2012/ISM/Chapter 4/Answers04…  · Web viewNotes: This project is an extension of a project from the previous chapter

21. Write an applet that displays a series of pictures of a person with arms, legs, and of course a head. Use a happy face for the head. Use ovals for the body, arms, and legs. Draw a sequence of figures that appear one after the other, as in Listing 4.9. Make the figures assume a running position. Change the color of the person’s face in each succeeding figure, going from white to pink to red to yellow to green. Have the smiling face gradually change its mouth shape from a smile on the first person to a frown on the last person. Use a switch statement to choose the color. Embed the switch statement in a loop.

Notes:

This applet is based on the MultipleFaces.java program in Listing 4.9. Rather than using odd and even counter values to determine color, this program uses a switch to determine the face color and the height adjustment of the mouth. The mouth height adjustment is used to gradually change the mouth from a smile to a frown. Also, a number of constants are added for the position and size of the arms, legs, and body.

References:

Listing 4.9

Solution:

See the code in RunningFaces.java and runningfaces.html.