Hints for Java Revel Quizzes and Programming Projects
Introduction to Java Programming and Data Structures 13E by Y. Daniel Liang
If you see any errors or have comments or suggestions, please email me at y.daniel.liang@gmail.com.
Please check this page often. We update this page frequently in response to student questions. Last update:
.
NOTE: Revel assigned exercises are currently submitted to a Java 11 compiler. Use the CheckExercise tool from
https://liveexample.pearsoncmg.com/CheckExercise/faces/CheckExercise13e.xhtml
to automatically check your code for logic errors before
submitting to Revel.
Errata can be viewed at https://liveexample.pearsoncmg.com/erratajava13e.html
Hints for End-of-Chapter Assignments (Programming Projects):
Chapter 1: Programming Project 1:
Click Exercise01_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Please check your spelling of the words carefully. It is case sensitive. The words are separated by exactly one space.
Chapter 1: Programming Project 2:
Click Exercise01_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Write the Math expression as (9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5).
Chapter 1: Programming Project 3:
Click Exercise01_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Use 1.0 instead of 1 in your program.
Chapter 1: Programming Project 4:
Click Exercise01_01Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
In this case, a is 3, b is 4, and c is 5. So, the discriminant for the equation 3x^2 + 4x + 5 is 4 * 4 - 4 * 3 * 5.
Chapter 1: Programming Project 5:
Click Exercise01_02Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The values for v0, v1, and t are given. Use these values in the formula to compute the average acceleration.
Chapter 2: Programming Project 1:
Click Exercise02_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
How would you write this program? Here are some hints:
Step 1: Prompt the user to enter subtotal and gratuity rate into variables subtotal (double) and gratuityRate (double). Note the gratuityRate is in percent. For example, if it is 15%, you enter 15 as the input for gratuityRate.
Step 2: Compute gratuity: gratuity = subtotal * gratuityRate / 100.
Step 3: Compute total: total = subtotal + gratuity.
Step 4: Display gratuity and total. Note you need to first display gratuity and then total. For all the programming projects, please pay attention to output order.
Chapter 2: Programming Project 2:
Click Exercise02_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
You must use the int or long type for all variables in this program. See LiveExample 2.5 in Section 2.9 for reference.
Now, the key to solve this problem is to use the correct math.
Step 1: Prompt the user to enter the minutes.
Step 2: Get the totalNumberOfDays from the minutes (i.e., totalNumberOfDays = minutes / (24 * 60)).
Step 3: Get the numberOfYears from the numberOfDays (i.e., numberOfYears = numberOfDays / 365).
Step 4: Get the remainingNumberOfDays from totalNumberOfDays (i.e., remainingNumberOfDays = totalNumberOfDays % 365).
Chapter 2: Programming Project 3:
Click Exercise02_15 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter two points. Each point has two values for x- and y-coordinates (double).
Step 2: Compute the distance using the distance formula given in the problem description. The correct formula for computing the distance is Math.pow((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1), 0.5)
Step 3: Display the result.
Chapter 2: Programming Project 4:
Click Exercise02_19 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter three points. Each point has two values for x- and y-coordinates (double).
Step 2: Compute side1, side2, and side3 using the distance formula given in the preceding project.
Step 3: Compute s using the formula s = (side1 + side2 + side3) / 2.
Step 4: Compute area using the formula given in the problem description.
Step 5: Display the result.
Chapter 2: Programming Project 5:
Click Exercise02_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The annualInterestRate (double) is entered in percentage. In the formula, you need to use monthlyInterestRate (double), which is annualInterestRate / 1200. See LiveExample 2.9 in Section 2.16 for reference.
Chapter 3: Programming Project 1:
Click Exercise03_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter a, b, c. Numbers are double.
Step 2: Compute discriminant.
Step 3: if (discriminant < 0), display "The equation has no real roots".
Step 4: else if (discriminant == 0), compute and display one root.
Step 5: else compute and display two roots.
Common errors from this project: In Step 1, your code should read in float values. In Step 2, discriminant is discriminant = b * b - 4 * a * c. In Step 5, please note that root1 is r1 = (-b + discriminant ** 0.5) / (2 * a). Another common mistake is to compute the roots before the if statement. Please compute roots in Step 5.
Chapter 3: Programming Project 2:
Click Exercise03_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter a, b, c, d, e, f. Numbers are double.
Step 2: Compute detA = a * d - b * c.
Step 3: if (detA == 0), display "The equation has no solution".
Step 4: else compute x and y, and display the result.
Common errors from this project: A common mistake is to compute x and y before the if statement. Please compute x and y in Step 4.
Chapter 3: Programming Project 3:
Click Exercise03_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
To test if a year is a leap year, see Section 3.11. Check your spelling on the month names to avoid errors.
Chapter 3: Programming Project 4:
Click Exercise03_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Prompt the user to enter year, month, and dayOfMonth. Note that all input are integers. You need to adjust year and month as follows:
if month is 1, set month = 13 and year = year - 1.
if month is 2, set month = 14 and year = year - 1.
You can now use Zeller’s formula to compute h.
Chapter 3: Programming Project 5:
Click Exercise03_23 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
A point (x, y) is in the rectangle centered at (0, 0) with width 10 and height 5 if |x| <= 5 and |y| <= 2.5. That is, x <= 5 && x >= -5 && y <= 2.5 && y >= -2.5. x and y are double.
Chapter 4: Programming Project 1:
Click Exercise04_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter numberOfSides as an int.
Step 2: Prompt the user to enter the length of a side as a double.
Step 3: Use the formula to compute the area. Use Math.PI for PI.
Step 4: Display the result.
Chapter 4: Programming Project 2:
Click Exercise04_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter decimal (int).
Step 2: if decimal is < 0 or > 15, display an error as shown in the sample output.
Step 3: else if decimal is < 10, simply display decimal.
Step 4: else display 'A' + decimal - 10.
Chapter 4: Programming Project 3:
Click Exercise04_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Prompt the user to enter a string into s using input.nextLine().
Step 2: if (s.length() != 1), display an error message as shown in the sample output.
Step 3: Get the first character from the string into ch.
Step 4: Convert ch into uppercase letter.
Step 5: if ch is not a letter, display an error message as shown in the sample output.
Step 6: else if ch is a vowel, display an appropriate message.
Step 7: else display an appropriate message for ch is a consonant.
Chapter 4: Programming Project 4:
Click Exercise04_17 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Prompt the user to enter year (int) and a string for month, and displays the number of days in the month. To test if a string is "Jan", use s.equals("Jan").
To test if a year is a leap year, see Section 3.11.
Chapter 4: Programming Project 5:
Click Exercise04_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
You will need to use s.length(), s.charAt(i), and Character.isDigit(ch) method in the program.
Step 1: Prompt the user to enter a string s for SSN.
Step 2: Declare a boolean variable named isValid and assign the conjunction of the following to isValid:
The length of s is exactly 11.
The character at index 0, 1, 2 are digits.
The character at index 3 is '-'.
The character at index 4, 5 are digits.
The character at index 6 is '-'.
The character at index 7, 8, 9 are digits.
Step 3: Display the result based on the value of isValid.
Chapter 5: Programming Project 1:
Click Exercise05_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Declare and initialize variables. Your program needs to count the number of positives, number of negatives, and total. Think about what initial values are appropriate for these variables. Note that the average can be computed using total / (numberOfPositives + numberOfNegatives).
Step 2: Prompt the user to read a number into variable number.
Step 3: Write a while loop to do the following:
Step 3.1: the loop continuation condition is (number =! 0)
Step 3.2: If number > 0, increase numberOfPositives by 1; if number < 0, increase numberOfNegatives by 1.
Step 3.3: Add number to total.
Step 3.4: Prompt the user to a new input and assign it to number.
Step 4: After the loop is finished, if (numberOfPositives + numberOfNegatives == 0), this means "No numbers are entered except 0". Your program should display exactly this message. Otherwise, display the number of positives, negatives, and average. To compute average, use 1.0 * total / (numberOfPositives + numberOfNegatives).
Chapter 5: Programming Project 2:
Click Exercise05_41 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Maintain two variables (int), max and count. max stores the current max number and count stores its occurrences.
Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment count by 1
Step 1: Declare two integer variables max and count. count is initialized to 0.
Step 2: Read the first number and assign it to max.
Step 3: Write a loop that continues to read an integer. When the integer is 0, the loop ends.
Step 4: For each integer read, if the integer is greater than max, assign it to max and reset count to 1, else if the integer is equal to max, increase count by 1.
Step 5: After the loop is finished, display max and count as shown in the sample run.
Chapter 5: Programming Project 3:
Click Exercise05_09 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Note that we assume that the number of students is at least 2. Use double for score. So use nextDouble() to read a score. So, your program does not need to consider the case for one or no students.
Step 1: Prompt the user to read the number of the students into variable numberOfStudents (int).
Step 2: Prompt the user to read first student name into student1(String) using input.next().
Step 3: Prompt the user to read first student score into score1 (double) using input.nextDouble().
Step 4: Prompt the user to read second student name into student2 (String) using input.next().
Step 5: Prompt the user to read second student score into score2 (double) using input.nextDouble().
Step 6: If (score1 < score2), swap student1 with student2 and score1 with score2. Throughout the program, we will use student1 and score1 to store the student name and score with the highest score and student2 and score1 to store the student name and score with the second highest score.
Step 7: Now write a loop to read the next student name and score. Consider the following cases:
Step 7.1: if (score > score1), assign score1 to score2 and score to score1, student1 to student2 and name to student.
Step 7.2: else if (score1 > score2), assign score to score2 and name to student2.
Step 8: Display the top two students’ name and score.
Chapter 5: Programming Project 4:
Click Exercise05_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
For this program, you need to use the formula for computing monthlyPayment and totalPayment in Section 2.16.
Step 1: Prompt the user to read loanAmount (double) and numberOfYears (int).
Step 2: Print the header using System.out.printf("%-20s%-20s%-20s\n", "Interest Rate", "Monthly Payment", "Total Payment");
Step 3: Write a for loop as follows:
Step 3.1: The initial action is to declare and initialize annualInterestRate to 5.0.
Step 3.2: The loop continuation condition is <= 8.0.
Step 3.3: The action after each iteration is annualInterestRate += 1.0/ 8.
Step 3.4: In the loop body, compute monthlyPayment and totalPayment using the formula. Note the monthlyInterestRate is annualInterestRate / 1200. Display annualInterestRate, monthlyPayment, and totalPayment in one line using printf to format the output. Please note: in the first column, you need to put three digits after the decimal point. For example, 5.000% is correct, but 5% is wrong.
Chapter 5: Programming Project 5:
Click Exercise05_49 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Declare and initialize variables numberOfVowels and numberOfConsonants with 0.
Step 2: Prompt the user to enter a string using input.nextLine().
Step 3: For each character in the string, do the following:
Step 3.1: Convert the character to uppercase.
Step 3.2: If the character is 'A', 'E', 'I', 'O', or 'U', increase numberOfVowels by 1.
Step 3.3: else if the character is a letter, increase numberOfConsonants by 1.
Step 4: Display the result using the wording as shown in the sample output.
Chapter 5: Programming Project 6:
Click Exercise05_47 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Step 1: Prompt the user to enter the first 12 digits of an ISBN-13 as a string s using input.nextLine
Step 2: If the length of the input is not 12, exit the program using System.exit(1). Note that since REVEL cannot handle System.exit(int), use "return" to replace "System.exit(1).
Step 3: Declare and initialize variable sum. (In Step 4, we will compute sum. sum will be d1 + 3*d2 + d3 + 3*d4 +…+d11 + 3*d12. Note d1 is s.charAt(0), d2 is s.charAt(1), etc.)
Step 4: for each i from 0 to s.length() - 1, do the following:
Step 4.1: If (i % 2 is 0), add (s.charAt(i) - '0') to sum.
Step 4.2: else, add (s.charAt(i) - '0') * 3 to sum.
Step 5: Obtain checksum that is 10 - sum % 10.
Step 6: Display the entire ISBN-13 string whose last digit is checksum. Note that if checksum is 10, display digit 0.
Chapter 6: Programming Project 1:
Click Exercise06_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a public class named Exercise06_07.
Step 2: Add two methods: the main method and the futureInvestmentValue method.
Step 3: Implement the futureInvestmentValue method to compute the futureInvestment value from investmentAmount, monthlyInterestRate and years using the formula from Exercise 2.21 in Chapter 2. This method return futureInvestmentValue.
Step 4: Implement the main method as follows:
Step 4.1: Prompt the user to enter investmentAmount (double) and annualInterestRate (double).
Step 4.2: Write a for loop as follows: for each year from 1 to 30, display year and the result from invoking futureInvestmentValue(investmentAmount, annualInterestRate / 1200, year). You need to use printf to display formatted output.
Chapter 6: Programming Project 2:
Click Exercise06_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a public class named Exercise06_13.
Step 2: Add two methods: the main method and the m(int i) method.
Step 3: Implement the m(int i) method to return the summation as shown in the formula for m(i) given in the description.
Step 3.1: declare and initialize sum.
Step 3.2: for each k from 1 to i, add k / (k + 1.0) to sum. Note we are using 1.0 rather than 1 to obtain a double result.
Step 3.3: return sum.
Step 4: Implement the main method as follows:
Step 4.1: Display the header of the table using printf. The header is "i m(i)".
Step 4.2: Write a for loop as follows: for each i from 1 to 20, display i and the result from invoking m(i). The result of m(i) is displayed with four digits after the decimal point. So, 0.5 should be displayed 0.5000 using printf.
Chapter 6: Programming Project 3:
Click Exercise06_23 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a public class named Exercise06_23.
Step 2: Add two methods: the main method and the count(String str, char a) method.
Step 3: Implement the count(String str, char a) as follows:
Step 3.1: declare and initialize count.
Step 3.2: for each i from 1 to str.length() - 1, if str.charAt(i) == a, increase count by 1.
Step 3.3: return count.
Step 4: Implement the main method as follows:
Step 4.1: Prompt the user to enter a string s using input.nextLine().
Step 4.2: Prompt the user to enter a char. To do so, read a line, and assign line.charAt(0) to character ch.
Step 4.3: Simply invoke count(s, ch) to return the count and display the result as shown in the sample run.
Chapter 6: Programming Project 4:
Click Exercise06_25 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
First, please read LiveExample 2.7 ShowCurrentTime.java in Section 2.12. This is very helpful for this exercise.
How would you write this program? Here are some hints:
Step 1: Create a public class named Exercise06_25.
Step 2: Add two methods: the main method and the convertMillis(long millis) method.
Step 3: Implement the convertMillis(long millis) method as follows:
Step 3.1: Obtain seconds from millis.
Step 3.2: Obtain totalMinutes from seconds.
Step 3.3: Obtain minutes from totalMinutes % 60.
Step 3.4: Obtain totalHours from totalMinutes / 60.
Step 3.5: Return a string: hours + ":" + minutes + ":" + seconds.
Step 4: Implement the main method as follows:
Step 4.1: Prompt the user to enter a long value using input.nextLong() into variable totalMillis.
Step 4.2: Invoke convertMillis(totalMillis) to return a string.
Step 4.3: Display this string.
Chapter 6: Programming Project 5:
Click Exercise06_37 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a public class named Exercise06_37.
Step 2: Add two methods: the main method and the format(int number, int width).
Step 3: Implement the format(int number, int width) method as follows:
Step 3.1: Assign number + "" to a String variable result.
Step 3.2: Obtain the numberOfDigits in number. For example, if number is 231, the numberOfDigits is 3. A simple way of obtaining numberOfDigits is (number + "").length(). number + "" is a string representation for number. Since result is number + "", numberOfDigits is result.length().
Step 3.3: Add width-numberOfDigits number of 0 before result. To accomplish this, write a for loop as follows: for each i from 1 to width - numberOfDigits, do result = "0" + result, which add a digit 0 before result.
Step 3.4: return result.
Step 4: Implement the main method as follows:
Step 4.1: Prompt the user to enter an integer number.
Step 4.2: Prompt the user to enter an integer width.
Step 4.3: Invoke format(number, width) to return a string and display it.
Chapter 7: Programming Project 1:
Click Exercise07_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Errata: In the project description, change > to >= four times.
Hint:
Step 1: Prompt the user to enter numberOfStudents (int).
Step 2: Create an array for scores using new double[numberOfStudents].
Step 3: Declare and initialize variable best to keep the best score. Set the initial value to 0.
Step 4: Prompt the user to enter the scores in a loop that executes numberOfStudents times. For each score entered, store it in scores[i]. Compare it with best. If it is greater than best, assign it to best.
Step 5: Write a for loop for i from 0 to numberOfStudents - 1, compare scores[i] with grade to assign the grade for the student.
Chapter 7: Programming Project 2:
Click Exercise07_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create an array for counts using new int[100]. count[0] will store the number of 1s entered and count[99] will store the number of 100 entered. By default, the count[i] is 0.
Step 2: Read a number.
Step 3: Write a while loop:
Step 3.1: The loop continuation condition is (number != 0).
Step 3.2: if number is between 1 and 100, count[number - 1]++.
Step 3.3: read the number again.
Step 4: Write a for loop to display the result as follows:
Step 4.1: for i from 0 to 99
Step 4.2: if counts[i] > 1, display number i + 1, counts[i] and "time" or "times". If (counts[i] > 1), displays "times". If (counts[i] == 1), display "time".
Chapter 7: Programming Project 3:
Click Exercise07_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create an array for numbers using new int[10].
Step 2: Declare and initialize an int variable numberOfDistinctValues (int).
Step 3: Write a for loop to execute 10 times. Each iteration of the loop performs the following actions:
Step 3.1: Read an int value.
Step 3.2: Test if value is already in numbers.
Step 3.3: if value is not numbers, add value to numbers: numbers[numberOfDistinctValues] = value.
Step 3.4: Increase numberOfDistinctValues by 1.
Step 4: Display the output: display numberOfDistinctValues and all the elements in numbers.
For Step 3.2, you may write a method
public static boolean isInNumbers(int[] numbers, int size, int value)
This method return true if value is equal to numbers[0], numbers[1], … numbers[size -1].
Chapter 7: Programming Project 4:
Click Exercise07_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a class named Exercise07_11.
Step 2: Add a main method, the mean method, and the deviation method in the class.
Step 3: Implement the mean(double[] x) method as follows:
Step 3.1: Declare and initialize a double variable sum.
Step 3.2: Write a loop to all elements in array x into sum.
Step 3.3: Return sum / x.length;
Step 4: Implement the deviation(double [] x) method as follows:
Step 4.1: Declare and initialize squareSum.
Step 4.2: Write a loop. For each element x[i], add (x[i] - mean(x)) ^ 2 to squareSum.
Step 4.3: return Math.sqrt(squareSum / (x.length - 1))
Step 5: Implement the main method as follows:
Step 5.1: Create an array numbers using new double[10].
Step 5.2: Prompt the user to enter 10 numbers and store them in numbers.
Step 5.3: Invoke mean(numbers) and deviation(numbers) to obtain mean and deviation for numbers.
Chapter 7: Programming Project 5:
Click Exercise07_19 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a class named Exercise07_19.
Step 2: Add a main method and the isSorted(int[] list) method in the class.
Step 3: Implement the isSorted(int[] list) method as follows:
Step 3.1: Write a for loop: for i from 0 to list.length - 2, if (list[i] > list[i + 1]), return false.
Step 3.2: If nothing is return in the for loop, return true after the for loop.
Step 4: Implement the main method as follows:
Step 4.1: Prompt the user to enter the size of list. Create list using new int[size].
Step 4.2: Prompt the user to enter int values for list.
Step 5: Invoke isSorted(list) to test if the elements in list are sorted.
Chapter 7: Programming Project 6:
Click Exercise07_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Arguments from the command line are passed to args in the main method.
How would you write this program? Here are some hints:
Step 1: Declare and initialize sum with 0.
Step 2: Write a for loop. For each args[i], add Integer.parseInt(args[i]) to sum.
Step 3: Display sum.
Chapter 8: Programming Project 1:
Click Exercise08_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint;
Step 1: Create a class named Exercise08_01.
Step 2: Add a main method and the sumColumn(double[][] m, int columnIndex)method in the class.
Step 3: Implement the sumColumn(double[][] m, int columnIndex)method as follows:
Step 3.1: Declare and initialize sum.
Step 3.2: Write a for loop: for i from 0 to m.length - 1, add m[i][columnIndex] to sum.
Step 3.3: Return sum.
Step 4: Implement the main method as follows:
Step 4.1: Declare a two-dimensional array m using new double[3][4].
Step 4.2: Write a nested for loop to obtain the input into m.
Step 4.3: Write a for loop. For each j from 0 to m[0].length - 1, invoke sumColumn(m, j) and display it.
Hint: Make sure you use the correct row and column size. The matrix has 3 rows and 4 columns.
Chapter 8: Programming Project 2:
Click Exercise08_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a class named Exercise08_05.
Step 2: Add three methods: a main method, addMatrix(double[][] m1, double[][] m2), and printResult(double[][] m1, double[][] m2, double[][] m3, char op) in the class.
Step 3: Implement the addMatrix(double[][] m1, double[][] m2)method as follows:
Step 3.1: Declare and initialize result using new double[m1.length][m1[0].length].
Step 3.2: Write a nested for loop to assign m1[i][j] + m2[i][j] to result[i][j].
Step 3.3: Return result.
Step 4: Implement the printResult(double[][] m1, double[][] m2, double[][] m3, char op) method as follows:
Step 4.1: For each row i from 0 to m1.length - 1, display a row in m1, m2, and m3. In the middle row, display the op between m1 and m2 and display the = symbol between m2 and m3.
Step 5: Implement the main method as follows:
Step 5.1: Create array m1. Enter input for m1.
Step 5.2: Create array m2. Enter input for m2.
Step 5.3: Obtain m3 from addMatrix(m1, m2).
Step 5.4: Display the result by invoking printResult(m1, m2, m3)
Chapter 8: Programming Project 3:
Click Exercise08_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a class named Exercise08_13.
Step 2: Add two methods:
a main method and
int[] locateLargest(double[][] a)
Step 3: Implement int[] locateLargest(double[][] a) to return the location of the largest element in an array. The first element in the array is the row index and the second is the column index. If there are more than one largest element, return the smallest row index and then the smallest column index.
Step 4: Implement the main method.
Step 4.1: Prompt the user to enter the number of rows and columns of the array.
Step 4.2: Create the array for the array.
Step 4.3: Prompt the user to enter the array.
Step 4.4: Invoke locateLargest(a) method to return the location of the largest element.
Step 4.5: Display the location of the largest element.
Chapter 8: Programming Project 4:
Click Exercise08_25 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Step 1: Create a class named Exercise08_25.
Step 2: Add two methods:
a main method and
boolean isMarkovMatrix(double[][] a)
Step 3: Implement boolean isMarkovMatrix(double[][] a) to test if the array is Markov array.
Step 4: Implement the main method.
Step 4.1: Prompt the user to enter the number of rows and columns of the array.
Step 4.2: Create the array for the array.
Step 4.3: Prompt the user to enter the array.
Step 4.4: Invoke isMarkovMatrix(a) method to return a boolean value.
Step 4.5: Display the result.
Chapter 8: Programming Project 5:
Click Exercise08_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
How would you write this program? Here are some hints:
Step 1: Create a class named Exercise08_21.
Step 2: Add three methods: a main method, distance(double[] c1, double[] c2), and totalDistance(double[][] cities, int i).
Step 3: Implement the main method.
Step 3.1: Prompt the user to enter numberOfCities.
Step 3.2: Create cities using new double[numberOfCities][2].
Step 3.3: Prompt the user to enter the coordinates for the cities.
Step 3.4: Declare minTotal (double) and minIndex (int) to store the minimum total distance and the index of the minimum total distance city.
Step 3.4: For every city with index i, invoke totalDistance(cities, i) to return the totalDistance. If it is < minTotal, assign totalDistance to minTotal and i to minIndex.
Step 3.5: Display the minTotal and minIndex for the central city.
Step 4: Implement distance(double[] c1, double[] c2). This method returns the distance between (c1[0], c1[1]) and (c2[0], c2[1]).
Step 5: Implement and totalDistance(double[][] cities, int i). This method returns the total distance from city i to all other cities.
Chapter 9: Programming Project 1:
Click Exercise09_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please note that you have to put all code in one file in order to submit to REVEL.
Your program should have no package statement. The outline of the program may look like this:
public class Exercise09_01 {
public static void main(String[] args) {
// Write your code
}
}
class Rectangle {
// Write your code
}
Chapter 9: Programming Project 2:
Click Exercise09_09 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please note that you have to put all code in one file in order to submit to REVEL. Your program should have no package statement. The outline of the program may look like this:
public class Exercise09_09 {
public static void main(String[] args) {
// Write your code
}
}
class RegularPolygon {
// Write your code
}
Chapter 9: Programming Project 3:
Click Exercise09_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please note that you have to put all code in one file in order to submit to REVEL. Your program should have no package statement. The outline of the program may look like this:
import java.util.Scanner;
public class Exercise09_13 {
public static void main(String[] args) {
// Write your code
}
public static Location locateLargest(double[][] a) {
// Write your code
// Hint for creating a Location object.
// Assume the max value in a is m and location is at (x, y)
Location location = new Location();
location.maxValue = m; location.x = x; location.y = y;
return location;
}
}
class Location {
// Write your code
}
Chapter 10: Programming Project 1:
Click Exercise10_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please note that you have to put all code in one file in order to submit to REVEL. Your program should have no package statement. The outline of the program may look like this:
public class Exercise10_01 {
public static void main(String[] args) {
Time time1 = new Time();
System.out.println(time1.getHour() + ":" +
time1.getMinute() + ":" + time1.getSecond());
Time time2 = new Time(555550000);
System.out.println(time2.getHour() + ":" +
time2.getMinute() + ":" + time2.getSecond());
Time time3 = new Time(5, 23, 55);
System.out.println(time3.getHour() + ":" +
time3.getMinute() + ":" + time3.getSecond()); }
}
class Time {
// Write your code
// Hint for finding hour, minute, second from elapse time.
// See LiveExample 2.7 for extracting hour, minute,
// and second from the elapse time.
}
Chapter 10: Programming Project 2:
Click Exercise10_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please
use the template at https://liveexample.pearsoncmg.com/test/Exercise10_03.txt for your code.
Chapter 10: Programming Project 3:
Click Exercise10_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Please note that you have to put all code in one file in order to submit to REVEL. Your program should have no package statement. The outline of the program may look like this:
public class Exercise10_11 {
public static void main(String[] args) {
// Write your code
}
}
class Circle2D {
// Write your code
}
Chapter 10: Programming Project 4:
Click Exercise10_17 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Here are some hints:
1. Use the BigInteger class to create big integer objects. To create a BigInteger for Long.MAX_VALUE, use new BigInteger(Long.MAX_VALUE + "").
2. Find the first n such that n^2 is greater than Long.MAX_VALUE.
3. The ten square numbers are n^2, (n+1)^2, (n+2)^, ... (n+9)^2
Chapter 11: Programming Project 1:
Click Exercise11_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
The outline of the program may look like this:
import java.util.Scanner;
import java.util.ArrayList;
public class Exercise11_13 {
public static void main(String[] args) {
// Write your code
}
public static void removeDuplicate(ArrayList list) {
// Write your code
}
}
Chapter 11: Programming Project 2:
Click Exercise11_15 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Two possible solutions:
1. You may break the polygon into triangles and compute the areas of the triangles
and add these areas to obtain the area of the polygon.
2. You may use the formula for computing the area of a polygon,
see http://www.mathwords.com/a/area_convex_polygon.htm. When using this formula, please note that
(1) the points entered in the description are in the clockwise order, but the points in the formula are in the counter clockwise order. You need to reverse the input order to apply the formula.
(2) the first point appears at the top and also at the bottom of the formula. If you use an array to store the points, you need to store the points in both the first and last of the array.
Chapter 11: Programming Project 3:
Click Exercise11_17 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Store all smallest factors of m into an array list. n is the product of the factors that appear an odd number of
times in the array list. For example, consider m = 90, store the factors 2, 3, 3, 5 in an array list. 2 and 5
appear an odd number of times in the array list. Thus, n is 10.
Chapter 12: Programming Project 1:
Click Exercise12_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
1. Check usage. For all programs that receive command-line arguments, always check usage.
See Section 7.13.
2. Check if the file exists.
3. Use the length() method in the File class to return
the number of characters. This will count all characters including white space characters.
4. Read each word line from the file using input.next(). 5. Close the file and reopen it. Read each line using input.nextLine().
Due to my server security restriction, the user is not allowed to read/write files on the server.
You cannot test Exercise12_13 from CheckExercise. However, you can test your code using Test1.txt and Test2.txt.
Download these two files from https://liveexample.pearsoncmg.com/test/TestExercise12_13.zip and
Test2.txt. If your output matches the following
two screen shots (character by character), your code is correct.
Chapter 12: Programming Project 2:
Click Exercise12_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Please read Section 6.7. Section 6.7 gives a program that converts a hex number to a decimal. This program is to convert a
binary to decimal. These two programs are very similar. You just have to make small changes. The radix for hex number 16, but
radix for binary number is 2 for this program.
Throw NumberFormatException if a binary digit is incorrect.
Chapter 12: Programming Project 3:
Click Exercise12_08Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Use the template at https://liveexample.pearsoncmg.com/test/Exercise12_08Extra.txt to write your code.
Chapter 13: Programming Project 1:
Click Exercise13_15 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 13: Programming Project 2:
Click Exercise13_17 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 13: Programming Project 3:
Click Exercise13_19 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 13: Programming Project 4:
Click Exercise13_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 18: Programming Project 1:
Click Exercise18_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The BigInteger class is introduced in Section 10.9. Please review LiveExample 10.9 for using BigInteger.
Chapter 18: Programming Project 2:
Click Exercise18_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The program contains the main function and the gcd(int m, int n). The main function prompts the user for the input m and n.
It then invokes gcd(m, n) to return the GCD of m and n.
gcd(m, n) returns n
if m % n is 0. Otherwise, gcd(m, n) is return gcd(n, m % n).
Chapter 18: Programming Project 3:
Click Exercise18_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The program contains the main method and the sumDigits(long n).
The main method prompts the user for the input number n. It then invokes sumDigits(n) to return the sum of the digits in n.
sumDigits(n) returns n if n is a single digit. Otherwise, it returns sumDigits(n / 10) + sumDigits(n % 10). n % 10 is the last digit in n. n / 10 is the remaining number after removing the last digit.
Chapter 18: Programming Project 4:
Click Exercise18_17 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The program contains the main method and two overloaded count methods. The main method prompts the user for the input string and then a character. It then converts the string into an array of characters by invoking the toCharArray method.
The count(char[] chars, char ch) method invokes count(chars, ch, chars.length - 1).
The count(char[] chars, char ch, int high) is a recursive helper method. The method returns 0 if high < 0. Otherwise, it returns count(chars, ch, high - 1) + (chars[high] == ch ? 1 : 0).
Chapter 18: Programming Project 5:
Click Exercise18_21 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
For simplicity, you can assume that the decimal integer is greater than 0. Your submission will work with this assumption.
The program contains the main method and the dec2Bin method. The main method prompts the user to enter an integer then invokes the dec2Bin(int) to return a binary string for the integer. It displays the binary string.
The dec2Bin(int value) method returns "" if value is 0, otherwise, it returns dec2Bin(value / 2) + value % 2.
Note that dec2Bin(value / 2) returns a string. value / 2 is 0 or 1. dec2Bin(value / 2) + value % 2 is a string.
Chapter 19: Programming Project 1:
Click Exercise19_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
There is an error in the description. The method header should be
public static <E extends Comparable<E>> E max(E[] list)
Chapter 19: Programming Project 2:
Click Exercise19_09 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
This program is similar to LiveExample 19.4 in Section 19.5. iveExample 19.4 uses selection sort for arrays. In this program, you need to sort an array list.
Chapter 20: Programming Project 1:
Click Exercise20_10 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 20: Programming Project 2:
Click Exercise20_23 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Study the code in LiveExample 20.12 in Section 20.11 using some samples, for example, 1+2, 2 * 3 - 3, etc.
Modify the example EvaluateExpression.java incrementally. One step at a time and you will know which step you are struggling.
Step 1. Read the input expression from the console rather than passing from the command line. (The code in the example passes the expression from the command line.)
Step 2. The operator % can be implemented similar to the * and / operators. Add the code for processing % in lines 51-61 in LiveExample 20.12.
Step 3. The operator ^ has the highest precedence. However, note that the ^ operator is right-associative, meaning that 2 ^ 3 ^ 2 is same as 2 ^ (3 ^ 2). In lines 51-61 in LiveExample 20.12, the program processes the * and / operators, add the code for processing the ^ operator after this block.
Watch the last 11 minutes in this VIDEO for additional help.
Chapter 21: Programming Project 1:
Click Exercise21_05Extra to
use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use TreeSet for this program.
Use addAll, removeAll, and retainAll to perform union, difference, and intersection. You need to clone a set before performing these operations so not to corrupt
the original set.
Chapter 21: Programming Project 2:
Click Exercise21_06Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Correction: There is an error in the sample run. It should be
Enter a string: Welcome to Java
c: 1
j: 1
l: 1
m: 1
t: 1
v: 1
w: 1
a: 2
e: 2
o: 2
Hint: See Section 21.6, toward the end of the section, there is a discussion on how to sort the entries on their values using the Collections.sort and Comparator.
Chapter 22: Programming Project 1:
Click Exercise22_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The program contains the main method and the maxConsecutiveSortedSubstring method.
public static String maxConsecutiveSortedSubstring(String s)
Implement the maxConsecutiveSortedSubstring method as follows:
Create an array:
int[] maxConsecutiveLength = new int[s.length()];
Compute the length of the max consecutive subsequence starting at index i for every i and save it in
maxConsecutiveLength[i].
Chapter 22: Programming Project 2:
Click Exercise22_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
The program contains the main method and the match method.
public static int match(String s, String pattern)
Implement the match method as follows:
Compare pattern with the substring in s starting from index 0. If a mismatch occurs at index i in s, slide the pattern past the mismatched character in s and continue to compare the
pattern with the substring in s.
Chapter 22: Programming Project 3:
Click Exercise22_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Hint:
Introduce the variables:
int longestSequenceCount = 0;
int longestSequenceValue = 0;
int longestSequenceIndex = 0;
Use these variables to track the longest sequence count, longest sequence value, and the starting index for the longest sequence.
Write a loop to read the input and update these variables. You don't need to store integers into an array or array list for this program.
Chapter 23: Programming Project 1:
Click Exercise23_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 24: Programming Project 1:
Click Exercise24_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Note: There is an errata for this exercise at https://liveexample.pearsoncmg.com/erratajava13e.html
Chapter 24: Programming Project 2:
Click Exercise24_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 25: Programming Project 1:
Click Exercise25_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
For the definition of the height of a binary tree, see Section 25.2. Use recursion. If the tree is empty (i.e., root is null), return -1, else return 1 + the max of the height of the left and right subtrees.
Use the code template from the project description to complete the exercise.
Chapter 25: Programming Project 2:
Click Exercise25_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Copy the height() method from the preceding project. You can compare the tree size with 2^(height+1) - 1 to determine if the tree is perfect.
Chapter 25: Programming Project 3:
Click Exercise25_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use recursion. If the tree is empty (i.e., root is null), return 0, else return 1 + the number of the non-leaf nodes in the left subtree + the number of the non-leaf nodes in the right subtree.
Chapter 25: Programming Project 4:
Click Exercise25_05Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 26: Programming Project 1:
Click Exercise26_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Note the height() method is already given. Use recursion. If the tree is empty (i.e., root is null), return true, else do the following:
1. Get the height of the left subtree in height1.
2. Get the height of the right subtree in height2.
3. Return isAVLTree(root.left) && isAVLTree(root.right) && Math.abs(height1 - height2) <= 1.
Chapter 27: Programming Project 1:
Click Exercise27_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 27: Programming Project 2:
Click Exercise27_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 28: Programming Project 1:
Click Exercise28_20Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 28: Programming Project 2:
Click Exercise28_05 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 29: Programming Project 1:
Click Exercise29_04Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 29: Programming Project 2:
Click Exercise29_05Extra to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Use the code template from the project description to complete the exercise.
Chapter 30: Programming Project 1:
Click Exercise30_01 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Chapter 30: Programming Project 2:
Click Exercise30_07 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Chapter 30: Programming Project 3:
Click Exercise30_03 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Chapter 30: Programming Project 4:
Click Exercise30_13 to use the CheckExerciseTool to check and debug your code before submitting to Revel.
Chapter 30: Programming Project 5:
Click Exercise30_11 to use the CheckExerciseTool to check and debug your code before submitting to Revel.