Skip to main content
Logo image

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

Section 9.14 Exercises

Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.

Exercises Exercises

1. Java Concept Matching.

Fill In the Blanks.

Fill in the blanks.
2. .
The process of arranging an array’s elements into a particular order is known as .
3. .
One of the preconditions of the binary search method is that the array has to be .
4. .
An is an object that can store a collection of a fixed number of elements of the same type.
5. .
An is like an array except that it can grow.
6. .
For an array, its is represented by an instance variable.
7. .
An expression that can be used during array instantiation to assign values to the array is known as an .
8. .
A is an array of arrays.
9. .
A sort method that can be used to sort different types of data is known as a method.
10. .
To instantiate an array you have to use the operator.
11. .
An array of objects stores to the objects.

Declaring Arrays.

Make each of the following array declarations:
12. .
A \(4 \times 4\) array of double s.
13. .
A \(20 \times 5\) array of String s.
14. .
A \(3 \times 4\) array of char initialized to ‘*’;
15. .
A \(2 \times 3 \times 2\) array of boolean initialized to true.
16. .
A \(3 \times 3\) array of Student s.
17. .
A \(2 \times 3\) array of String s initialized to “one,” “two,” and so on.

Syntax Errors.

Identify and correct the syntax error in each of the following expressions:
18. .
int arr = new int[15];
19. .
int arr[] = new int(15);
20. .
float arr[] = new [3];
21. .
float arr[] = new float {1.0,2.0,3.0};
22. .
int arr[] = {1.1,2.2,3.3};
23. .
int arr[][] = new double[5][4];
24. .
int arr[][] = { {1.1,2.2}, {3.3, 1} };

Evaluate Array Expressions.

Evaluate each of the following expressions, some of which may be erroneous:
int arr[] = { 2,4,6,8,10 };
25. .
arr[4]
26. .
arr[ arr.length ]
27. .
arr[ arr[0] ]
28. .
arr[ arr.length / 2 ]
29. .
arr[ arr[1] ]
30. .
arr[ 5 % 2 ]
31. .
arr[ arr[ arr[0] ] ]
32. .
arr[ 5 / 2.0 ]
33. .
arr[ 1 + (int) Math.random() ]
34. .
arr[ arr[3] / 2 ]

35. One-D Trace.

What would be printed by the following code segment?
int arr[] = { 24, 0, 19, 21, 6, -5, 10, 16};
for (int k = 0; k < arr.length; k += 2)
  System.out.println( arr[k] );

36. Two-D Trace.

What would be printed by the following code segment?
int arr[][] = { {24, 0, 19}, {21, 6, -5}, {10, 16, 3},
                                           {1, -1, 0} };
for (int j = 0; j < arr.length; j++)
  for (int k = 0; k < arr[j].length; k++)
    System.out.println( arr[j][k] );

37. Two-D Trace 2.

What would be printed by the following code segment?
int arr[][] = { {24, 0, 19}, {21, 6, -5}, {10, 16, 3},
                                           {1, -1, 0} };
for (int j = 0; j < arr[0].length; j++)
    for (int k = 0; k < arr.length; k++)
        System.out.println(arr[k][j]);

38. Swap Error.

What’s wrong with the following code segment, which is supposed to swap the values of the int variables, n1 and n2?
int temp = n1;
n2 = n1;
n1 = temp;

39. Swap Method.

Explain why the following method does not successfully swap the values of its two parameters?
Hint.
public void swapEm(int n1, int n2) {
    int temp = n1;
    n1 = n2;
    n2 = temp;}

40. Create an Array.

Declare and initialize an array to store the following two-dimensional table of values:
1   2   3   4
5   6   7   8
9  10  11  12

41. Print Column by Column.

For the two-dimensional array you created in the previous exercise, write a nested for loop to print the values in the following order: 1 5 9 2 6 10 3 7 11 4 8 12. That is, print the values going down the columns instead of going across the rows.

Defining Arrays.

Define an array that would be suitable for storing the following values:
42. GPA Array.
The GPAs of 2,000 students.
43. Rectangle Sides Array.
The lengths and widths of 100 rectangles.
44. Temperature Array.
A week’s worth of hourly temperature measurements, stored so that it is easy to calculate the average daily temperature.
45. Tic Tac Tow Array.
A board for a tic-tac-toe game.
46. 50 States Array.
The names and capitals of the 50 states.

47. Sum Array.

Write a code segment that will compute the sum of all the elements of an array of int.

48. Sum 2D Arrray.

Write a code segment that will compute the sum of the elements in a two-dimensional array of int.

Writing Array Methods.

Each of the problems that follow asks you to write a method. Of course, as you are developing the method in a stepwise fashion, you should test it. Here’s a simple application program that you can use for this purpose:
import java.util.Arrays;

public class MethodTester {
    public static String stringify(Object[] s) {
        StringBuffer sb = new StringBuffer();
        int width = 0;
	final int MAX_WIDTH = 60;
	for(Object o : s) {
	   if(width + o.toString().length() >= MAX_WIDTH) {
	      sb.append("\n");
	      width = 0;
	   }
           sb.append(o.toString());
	   sb.append(",");
	   width += o.toString().length() + 1;
	}
	if (sb.charAt(sb.length()-1) == ',') {
           sb.deleteCharAt(sb.length()-1);
	   sb.append("\n");
	}

	return sb.toString();
    }
    public static void main(String args[]) {
        Integer[] x = new Integer[100];
        Arrays.fill(x,12345);
        System.out.println("the array is:\n" + stringify(x));
    }
}
Just replace the stringify() method with your method. Note that you must declare your method static if you want to call it directly from main() as we do here.
49. Array Average Method.
Write a method that will compute the average of all the elements of a two-dimensional array of float.
50. Find Last Greater.
Write a method that takes two parameters, an int array and an integer, and returns the location of the last element of the array that is greater than or equal to the second parameter.

51. Test Magic Square.

Write a program that tests whether a \(3\; \times \;3\) array, input by the user, is a magic square. A magic square is an \(N\; \times\; N\) matrix of numbers in which every number from 1 to \(N^2\) must appear just once, and every row, column, and diagonal must add up to the same total—for example,
6 7 2
1 5 9
8 3 4

52. Test Bigger Magic Square.

Revise the program in the previous exercise so that it allows the user to input the dimensions of the array, up to \(4\; \times\; 4\text{.}\)

53. Relative Frequencies.

Modify the AnalyzeFreq program so that it can display the relative frequencies of the 10 most frequent and 10 least frequent letters.

54. Sort Then Merge.

The merge sort algorithm takes two collections of data that have been sorted and merges them together. Write a program that takes two 25-element int arrays, sorts them, and then merges them, in order, into one 50-element array.

55. Implement BigInteger.

Challenge:: Design and implement a BigInteger class that can add and subtract integers with up to 25 digits. Your class should also include methods for input and output of the numbers. If you’re really ambitious, include methods for multiplication and division. (Do not use java.math.BigInteger for your implementation)

56. Client Purchases Structure.

Challenge:: Design a data structure for this problem: As manager of Computer Warehouse, you want to track the dollar amount of purchases made by those clients that have regular accounts. The accounts are numbered from 0, 1, ,N. The problem is that you don’t know in advance how many purchases each account will have. Some may have one or two purchases. Others may have 50 purchases.

57. Test Anagrams.

An anagram is a word made by rearranging the letters of another word. For example, act is an anagram of cat, and aegllry is an anagram of allergy. Write a Java program that accepts two words as input and determines if they are anagrams.

58. Anagram Dictionary.

Challenge:: An anagram dictionary is a dictionary that organizes words together with their anagrams. Write a program that lets the user enter up to 100 words (in a TextField, say). After each word is entered, the program should display (in a TextArea perhaps) the complete anagram dictionary for the words entered. Use the following sample format for the dictionary. Here the words entered by the user were: felt, left, cat, act, opt, pot, top.
act:  act cat
eflt:  felt left
opt:   opt pot top

59. Distance Class.

Acme Trucking Company has hired you to write software to help dispatch its trucks. One important element of this software is knowing the distance between any two cities that it services. Design and implement a Distance class that stores the distances between cities in a two-dimensional array. This class will need some way to map a city name, Boise, into an integer that can be used as an array subscript. The class should also contain methods that would make it useful for looking up the distance between two cities. Another useful method would tell the user the closest city to a given city.

60. Word Guess Game.

Rewrite the main() method for the WordGuess example so that it allows the user to input the number of players and whether each players is a computer or a human. Use a KeyboardReader.

61. Word Guesser Class.

Write a smarter version of the WordGuesser class that “knows” which letters of the English language are most frequent.
Hint.

62. Sliding Tiles CLI.

Write a command line interface, CLI, version of the SlidingTilePuzzle. You will need to make modifications to the SlidingTilePuzzle class.
You have attempted of activities on this page.