Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 1.9 Exercises

Exercises Java Programming Design and Development

Fill In the Blanks.

Fill in the blanks in each of the following statements.
1. Java class definition.
A Java class definition contains an object’s and .
2. Java method definition.
A method definition contains two parts, a and a .

3. Java Concept Matching.

Syntax vs. Semantics.

For each of the following, identify it as either a syntax error or a semantic error, and identify the best explanation.
4. Class Header.
    Write a class header as public Class MyClass.
  • syntax error, MyClass isn’t descriptive enough.
  • syntax error, Class is not a keyword. the keyword class starts with a lowercase character
  • semantic error, the class isn’t always mine.
  • semantic error, if the class is mine, then it should be private.
5. Method Header.
    Define the init() header as public vid init().
  • syntax error, vidis not a keyword understood by the compiler
  • syntax error, constructors don’t have a return type.
  • semantic error, returning a video instead of nothing doesn’t make sense.
  • semantic error, public methods can be called by any class.
6. Console output.
    Print a string of five asterisks by System.out.println("***");.
  • syntax error, the statement doesn’t return anything
  • syntax error, semicolons end every statement
  • semantic error, prints three asterisks instead of five.
  • semantic error, prints a newline after the string.
7. Missing semicolon.
    Forget the semicolon at the end of a println() statement.
  • syntax error, the statement doesn’t return anything
  • syntax error, semicolons are needed to end every statement
  • semantic error, we don’t know what the println() prints.
  • semantic error, prints a newline after the string.
8. Arithmetic.
    Variables n and m have been initialized as numeric data types. Calculate the sum of the two numbers as n - m.
  • syntax error, expressions can be part of larger statements
  • syntax error, semicolons are needed to end every statement
  • semantic error, It is correct syntax but the difference of n and m will be calculated instead of the sum.
  • semantic error, n and m could be any number that can be represented by the data type

9. Java compile and run.

Suppose you have a Java program stored in a file named Test.java. Describe the compilation and execution process for this program, naming any other files that would be created.

Algorithm Tracing.

Consider the following algorithm:
0. Print N.
1. If N equals 1, stop.
2. If N is even, divide it by 2,
3. Otherwise, triple it and add 1.
4. Go to step 0.
10. 7 sequence.
    Suppose N is 7. Select the sequence of numbers would be output by the above pseudocode algorithm.
  • 7,3,1
  • 7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
  • 7,20,10,5,14,7,...
  • 7,16,8,4,2,1
11. 6 sequence.
    Suppose N is 6. Select the sequence of numbers would be output by the above pseudocode algorithm.
  • 6,3,1
  • 6,3,10,5,16,8,4,2,1
  • 6,19,9,4,13,6,...
  • 6,3,8,4,2,1

12. Loop algorithm.

Suppose N is 5 and M is 3. What value would be reported by the following pseudocode algorithm? In general, what quantity does this algorithm calculate?
	  0. Write 0 on a piece of paper.
	  1. If M equals 0, report what's on the paper and stop.
	  2. Add N to the quantity written on the paper.
	  3. Subtract 1 from M.
	  4. Go to step 1.
	

13. Two ropes burning.

Puzzle Problem: You are given two different length ropes that have the characteristic that they both take exactly one hour to burn. However, neither rope burns at a constant rate. Some sections of the ropes burn very fast; other sections burn very slowly. All you have to work with is a box of matches and the two ropes. Describe an algorithm that uses the ropes and the matches to calculate when exactly 45 minutes have elapsed.

14. Polar mobility.

Puzzle Problem: A polar bear that lives right at the North Pole can walk due south for one hour, due east for one hour, and due north for one hour, and end up right back where it started. Is it possible to do this anywhere else on earth? Explain.

15. Tower puzzle.

Puzzle Problem: Lewis Carroll, the author of Alice in Wonderland, used the following puzzle to entertain his guests: A captive monarch weighing 195 pounds, her youngest child weighing 90 pounds, and her eldest weighing 165 pounds, were trapped in a very high tower. Outside their window was a pulley and rope with a basket fastened on each end. They managed to escape by using the baskets and a 75-pound weight they found in the tower. How did they do it? The problem is that anytime the difference in weight between the two baskets is more than 15 pounds, someone might get hurt. Describe an algorithm that gets them down safely.

16. River crossing.

Puzzle Problem: Here’s another Carroll favorite: A farmer needs to cross a river with a fox, a goose, and a bag of corn. There’s a rowboat that will hold the farmer and one other passenger. The problem is that the fox will eat the goose if they are left alone on the river bank, and the goose will eat the corn if they are left alone on the river bank. Write an algorithm that describes how they got all across without any losses. One last constraint is that the animals don’t like to stay still; so, prioritize getting the animals to the other side before the corn, if possible.

17. Weight Balancing.

Puzzle Problem: Have you heard this one? A farmer lent the mechanic next door a 40-pound weight. Unfortunately, the mechanic dropped the weight and it broke into four pieces. The good news is that, according to the mechanic, it is still possible to use the four pieces to weigh any quantity between one 40 pounds on a balance scale. How much did each of the four pieces weigh? Enter in order of increasing weight, the value of each weight fragment in pounds.
Hint 1.
Hint 2.

18. Calculator Algorithm.

Suppose your younger sibling asks you to show them how to use a pocket calculator so that they can calculate their homework average in their science course. Describe an algorithm that they can use to find the average of 10 homework grades.

19. Shift Cipher (a la Julius Caesar).

    A Caesar cipher is a secret code in which each letter of the alphabet is shifted by N letters to the right, with the letters at the end of the alphabet wrapping around to the beginning. For example, if N is 1, when we shift each letter to the right, the word daze would be written as ebaf. Note that the z has wrapped around to the beginning of the alphabet. Select each of the below algorithms that can be used to create a Caesar encoded message with a shift of 5.
  • Shift each letter of the message to the right by 5.
  • Yes, since letters are represented numerically, shifting to the right is equivalent to adding 5 to the value and subtracting 26 if the number is above 26.
  • 	      Repeat 5 times,
    	          Shift each letter of the message to the right by 1
    	    
  • Yes, this can be done with repetition or a loop.
  • Shift each letter of the message to the left by 21.
  • Yes, shifting to the left by 21 (subtract 21 and add 26 if the result is below 1) is the same as shifting to the right by 5
  • Shift each letter of the message to the right by 7.
  • No, that will shift too mucn.
  • 	      Repeat 3 times,
    	          Shift each letter of the message to the left by 7
    	    
  • Yes, this combines a loop, shifting to the left, and the fact that 21 can be factored into 3 and 7.

Shift Decipher.

Suppose you received the message, “sxccohv duh ixq,” which you know to be a Caesar cipher.
20. Decipher the Text.
Figure out what it says, type it in here:
21. Determine the Decipher algorithm.
    Then select which of the below algorithms will always find what the message said regardless of the size of the shift that was used.
  • Shift each letter of the message to the right by
    	  3.
  • Try again, this will only work if the encoding is a left shift of 3 or a right shift of 23.
  • Shift each letter of the message to the left by
    	  3.
  • Try again, this will only work if the encoding is a right shift of 3 or a left shift of 23.
  • 	      Repeat until the message has real words,
    	          Shift each letter of the message to the left by 1
    	    
  • Yes, this is a brute force solution that stops as soon as it finds a reasonable decoding.
  • 1. Select the smallest encoded word
    2.    let the shift amount be 0
    3.    Shift each letter of the message to the left by 1
    4.    increment the shift amount
    5.    if the smallest word is not a real word, goto 3
    6.    Shift the encoded phrase to the left by the shift amount
    7.    if the encoded phrase isn't only real words, goto 3
    	      
    	    
  • Yes, this is a brute force solution, with an optimization to search the smallest word as a first guess, then stops as soon as it finds a reasonable decoding.

22. Running average.

Suppose you’re talking to your younger sibling on the phone and they want you to calculate their homework average. All you have to work with is a piece of chalk and a very small chalkboard—big enough to write one four-digit number. What’s more, although your younger sibling knows how to read numbers, they don’t know how to count very well so they can’t tell you how many grades there are. All they can do is read the numbers to you. Describe an algorithm that will calculate the correct average under these conditions.

23. Method header.

Write a header for a public method named getName.

24. Rectangle class.

Design and implement a class to represent a geometric rectangle with a given length and width, such that it is capable of calculating the area and the perimeter of the rectangle. A main method for the class is below that should work once your class is fully implemented. (Note the tests will only work if you make all of your variables and return types as double.

25. Nursery Rhyme printing.

Modify the NurseryRhyme class to “sing” either “Mary Had a Little Lamb” or your favorite nursery rhyme instead of Old MacDonald had a farm.

26. Printing patterns.

Define a Java class, called Patterns, modeled after OldMacDonald, that will print the following patterns of asterisks, one after the other heading down the page:
	    *****     *****   *****
	     ****     *   *   * * *
	      ***     *   *    * *
               **     *   *   * * *
                *     *****   *****
	  

27. Printing Initials.

Write a Java class that prints your initials as block letters, as shown here:
	  ****** *     *
	  *    * **   **
	  *    * * * * *
	  ****** * * * *
	  **     *  *  *
	  * *    *     *
	  *  *   *     *
	  *   *  *     *
	

28. Temperature class.

Challenge: Define a class that represents a Temperature object. It should store the current temperature in an instance variable of type double, and it should have a public constructor Temperature(double t) that initializes the instance variable, and one public method, getTemp(), which returns the value of the instance variable. Use the Riddle class as a model.

29. Tax Whiz Challenge.

Challenge: Define a class named TaxWhiz that computes the sales tax for a purchase. It should store the current tax rate as an instance variable. Following the model of the Riddle class, you can initialize the rate using a TaxWhiz() constructor. This class should have one public method, calcTax(double purchase), which will return a double, whose value is purchases times the tax rate. For example, if the tax rate is 4 percent, 0.04, and the purchase is $100, then calcTax() should return 4.0.

30. Variable Tracing.

What is stored in the variables num1 and num2 after the following statements are executed?
int num1 = 5;
int num2 = 8;
num1 = num1 + num2;
num2 = num1 + num2;
	
Enter the final value for num1:
Enter the final value for num2:

31. Variable initialization.

Write a single of statement that will declare a variable of type int called num and store in it the difference between 61 and 51.

32. UML Riddle.

Modify the UML diagram of the Riddle class to contain a method named getRiddle() that would return both the riddle’s question and answer.

33. UML Circle.

Draw a UML class diagram representing the following class: The name of the class is Circle. It has one attribute, a radius that is represented by a double value. It has one operation, calculateArea(), which returns a double. Its attributes should be designated as private and its method as public.

34. UML Triangle.

To represent a triangle we need attributes for each of its three sides and operations to create a triangle, calculate its area, and calculate its perimeter. Draw a UML diagram to represent this triangle.

35. UML to Java.

Try to give the Java class definition for the class described in UML diagram shown here.
You have attempted of activities on this page.