New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
java concepts late objects
Java Concepts Late Objects 3rd Edition Cay S. Horstmann - Solutions
Use a stack to reverse the words of a sentence. Keep reading words until you have a word that ends in a period, adding them onto a stack. When you have a word with a period, pop the words off and print them. Stop when there are no more words in the input. For example, you should turn the input Mary
Repeat Exercise E15.22, but use a queue instead.Data from Exercise E15.22,In a paint program, a “flood fill” fills all empty pixels of a drawing with a given color, stopping when it reaches occupied pixels. In this exercise, you will implement a simple variation of this algorithm, flood-filling
Explain what the following code prints. Draw a picture of the linked list and the iterator position after each step.LinkedList staff = new LinkedList<>();ListIterator iterator = staff.listIterator();iterator.add("Tom");iterator.add("Diana");iterator.add("Harry");iterator =
Your task is to break a number into its individual digits, for example, to turn 1729 into 1, 7, 2, and 9. It is easy to get the last digit of a number n as n % 10. But that gets the numbers in reverse order. Solve this problem with a stack. Your program should ask the user for an integer, then
Use a stack to enumerate all permutations of a string. Suppose you want to find all permutations of the string meat. Push the string +meat on the stack. While the stack is not empty Pop off the top of the stack. If that string ends in a + (such as tame+) Remove the + and add the string to the list
You are given a linked list of strings. How do you remove all elements with length less than or equal to three?
A homeowner rents out parking spaces in a driveway during special events. The driveway is a “last-in, first-out” stack. Of course, when a car owner retrieves a vehicle that wasn’t the last one in, the cars blocking it must temporarily move to the street so that the requested vehicle can
Repeat Exercise P15.9, but use a queue instead.Data from Exercise P15.9,Use a stack to enumerate all permutations of a string. Suppose you want to find all permutations of the string meat. Push the string +meat on the stack. While the stack is not empty Pop off the top of the stack. If that string
Implement a to do list. Tasks have a priority between 1 and 9, and a description. When the user enters the command add priority description, the program adds a new task. When the user enters next, the program removes and prints the most urgent task. The quit command quits the program. Use a
An airport has only one runway. When it is busy, planes wishing to take off or land have to wait. Implement a simulation, using two queues, one each for the planes waiting to take off and land. Landing planes get priority. The user enters commands takeoff flightSymbol, land flightSymbol, next, and
What advantages do linked lists have over arrays? What disadvantages do they have?
Write a program that reads text from a file and breaks it up into individual words. Insert the words into a tree set. At the end of the input file, print all words, followed by the size of the resulting set. This program determines how many unique words a text file has.
Suppose you buy 100 shares of a stock at $12 per share, then another 100 at $10 per share, and then sell 150 shares at $15. You have to pay taxes on the gain, but exactly what is the gain? In the United States, the FIFO rule holds: You first sell all shares of the first batch for a profit of $300,
Suppose you need to organize a collection of telephone numbers for a company division. There are currently about 6,000 employees, and you know that the phone switch can handle at most 10,000 phone numbers. You expect several hundred lookups against the collection every day. Would you use an array
Insert all words from a large file (such as the novel “War and Peace”, which is available on the Internet) into a hash set and a tree set. Time the results. Which data structure is more efficient?
Extend Exercise P15.12 to a program that can handle shares of multiple companies. The user enters commands buy symbol quantity price and sell symbol quantity price. Hint: Keep a Map> that manages a separate queue for each stock symbol.Data from Exercise P15.12Suppose you buy 100 shares of a
Suppose you need to keep a collection of appointments. Would you use a linked list or an array list of Appointment objects?
Supply compatible hashCode and equals methods to the BankAccount class of Chapter 8. Test the hashCode method by printing out hash codes and by adding BankAccount objects to a hash set.
Consider the problem of finding the least expensive routes to all cities in a network from a given starting point. For example, in the network shown on the map on page 733, the least expensive route from Pendleton to Peoria has cost 8 (going through Pierre and Pueblo). The following helper class
Suppose you write a program that models a card deck. Cards are taken from the top of the deck and given out to players. As cards are returned to the deck, they are placed on the bottom of the deck. Would you store the cards in a stack or a queue?
Suppose the strings "A" . . . "Z" are pushed onto a stack. Then they are popped off the stack and pushed onto a second stack. Finally, they are all popped off the second stack and printed. In which order are the strings printed?
Reimplement the LabeledPoint class of Exercise E15.15 by storing the location in a java.awt.Point object. Your hashCode and equals methods should call the hashCode and equals methods of the Point class.Data from Exercise E15.15A labeled point has x- and y-coordinates and a string label. Provide a
What is the difference between a set and a map?
Can a map have two keys with the same value? Two values with the same key?
Add a % (remainder) operator to the expression calculator of Section 15.6.3.package collections;import java.util.Scanner;import java.util.Stack;public class ExpressionCalculator { public static void main(String[] args) { Scanner consoleIn = new
Modify the LabeledPoint class of Exercise E15.15 so that it implements the Comparable interface. Sort points first by their x-coordinates. If two points have the same x-coordinate, sort them by their y-coordinates. If two points have the same x- and y-coordinates, sort them by their label. Write a
How can you compute the union and intersection of two sets, using some of the methods that the java.util.Set interface provides, but without using an iterator? (Look up the interface in the API documentation.)
Write a program that checks whether a sequence of HTML tags is properly nested. For each opening tag, such as, there must be a closing tag. A tag such asmay have other tags inside, for example:The inner tags must be closed before the outer ones. Your program should process a file containing tags.
A map can be implemented as a set of (key, value) pairs. Explain.
How can you print all key/value pairs of a map, using the keySet method? The entrySet method? The forEach method with a lambda expression? (See Java 8 Note 9.3 on lambda expressions.)
In a paint program, a “flood fill” fills all empty pixels of a drawing with a given color, stopping when it reaches occupied pixels. In this exercise, you will implement a simple variation of this algorithm, flood-filling a 10 × 10 array of integers that are initially 0. Prompt for the
Verify the hash code of the string "Juliet" in Table 6.
Verify that the strings "VII" and "Ugh" have the same hash code.
Consider the algorithm for traversing a maze from Section 15.6.4 Assume that we start at position A and push in the order West, South, East, and North. In which order will the lettered locations of the sample maze be visited? P MN K GH A B DE
Repeat Exercise R15.25, using a queue instead of a stack.Data from Exercise R15.25,Consider the algorithm for traversing a maze from Section 15.6.4 Assume that we start at position A and push in the order West, South, East, and North. In which order will the lettered locations of the sample maze be
Write a method that tests whether a file name should come before or after another. File names are first sorted by their extension (the string after the last period) and then by the name part (the string that remains after removing the extension). For example, before("report.doc", "notes.txt")
Write a program that reads a decimal expansion with a repeated part, as in Exercise P5.16, and displays the fraction that it represents.Data from Exercise P5.16,Write a program that prints the decimal expansion of a fraction, marking the repeated part with an R. For example, 5/2 is 2.5R0, 1/12 is
Give pseudocode for a recursive method that sorts all letters in a string. For example, the string "goodbye" would be sorted into "bdegooy".
When comparing strings with compareTo, the comparison is not always satisfactory. For example, "file10".compareTo("file2") returns a negative value, indicating that "file10" should come before "file2", even though we would prefer it to come afterwards. Produce a numCompare method that, when
Write two methodspublic static void drawHouse(Graphics g, int x, int y)public static void drawCar(Graphics g, int x, int y)that draw a house or car at a given position. Then write a program that calls these methods to produce a suburban scene with several houses and cars.
Write a program that reads in the width and height of a rectangle and the diameter of a circle. Then fill the rectangle with as many circles as possible, using “square circle packing”:Read the inputs in the main method and pass them to the draw method. Provide a helper method to draw each row.
Write a program that prints a paycheck. Ask the program user for the name of the employee, the hourly rate, and the number of hours worked. If the number of hours exceeds 40, the employee is paid “time and a half”, that is, 150 percent of the hourly rate on the hours exceeding 40. Your check
Postal bar codes. For faster sorting of letters, the United States Postal Service encourages companies that send large volumes of mail to use a bar code denoting the zip code (see Figure 7). The encoding scheme for a five-digit zip code is shown in Figure 8. There are full-height frame bars on each
Write a program that reads in a bar code (with : denoting half bars and | denoting full bars) and prints out the zip code it represents. Print an error message if the bar code is not correct.
Write a program that converts a Roman number such as MCMLXXVIII to its decimal number representation. Hint: First write a method that yields the numeric value of each of the letters. Then use the following algorithm:total = 0str = roman number stringWhile str is not emptyIf str has length 1, or
A non-governmental organization needs a program to calculate the amount of financial assistance for needy families. The formula is as follows:• If the annual household income is between $30,000 and $40,000 and the household has at least three children, the amount is $1,000 per child.• If the
Write a recursive methodpublic static String reverse(String str) that computes the reverse of a string. For example, reverse("flow") should return "wolf". Hint: Reverse the substring starting at the second character, then add the first character at the end. For example, to reverse "flow", first
For each of the variables in the following program, indicate the scope. Then determine what the program prints, without actually running the program.1 public class Sample2 {3 public static void main(String[] args)4 {5 int i = 10;6 int b = g(i);7 System.out.println(b + i);8 }910 public static int
In Exercise P3.13 you were asked to write a program to convert a number to its representation in Roman numerals. At the time, you did not know how to eliminate duplicate code, and as a consequence the resulting program was rather long. Rewrite that program by implementing and using the following
Write methodspublic static double sphereVolume(double r)public static double sphereSurface(double r)public static double cylinderVolume(double r, double h)public static double cylinderSurface(double r, double h)public static double coneVolume(double r, double h)public static double
Describe the scope error in the following program and explain how to fix it.public class Conversation{public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("What is your first name? ");String input = in.next();System.out.println("Hello, " +
Leap years. Write a method public static boolean isLeapYear(int year)that tests whether a year is a leap year: that is, a year with 366 days. Exercise P3.14 describes how to test whether a year is a leap year. In this exercise, use multiple if statements and return statements to return the
Write a method that returns the average length of all words in the string str. Use the same helper methods as in Exercise E5.7.Data from Exercise E5.7.Write a methodpublic static int countWords(String str) that returns a count of all words in the string str. Words are separated by spaces.
Write pseudocode for a method that translates a telephone number with letters in it (such as 1-800-FLOWERS) into the actual phone number. Use the standard letters on a phone pad. O stacey_newman'iStoc kp hoto.
Use recursion to compute an, where n is a positive integer. Hint: If n is 1, then an = a. If n is even, then an = (an/2)2. Otherwise, an = a × an–1.
Write a methodpublic static int countWords(String str)that returns a count of all words in the string str. Words are separated by spaces. For example, countWords(" Mary had a little lamb") should return 5. Your method should work correctly if there are multiple spaces between words. Use helper
Design a method that prints a floating-point number as a currency value (with a $ sign and two decimal digits).a. Indicate how the programs ch02/sec03/Volume2.java and ch04/sec03/Investment- Table.java should change to use your method.b. What change is required if the programs should show a
Provide trace tables of the following loops.a. int s = 1;int n = 1;while (s < 10) { s = s + n; }n++;b. int s = 1;for (int n = 1; n < 5; n++){s = s + n;}c. int s = 1;int n = 1;do{s = s + n;n++;}while (s < 10 * n);
The game of Nim. This is a well-known game with a number of variants. The following variant has an interesting winning strategy. Two players alternately take marbles from a pile. In each move, a player chooses how many marbles to take. The player must take at least one but at most half of the
Write pseudocode for a program that prints a Celsius/Fahrenheit conversion table such as the following: Celsius | Fahrenheit -+- 32 10 | 20 | 50 68 100 | 212
Write a methodpublic static String repeat(String str, int n)that returns the string str repeated n times. For example, repeat("ho", 3) returns "hohoho".
Consider these methods:public static double f(double x) { return g(x) + Math.sqrt(h(x)); }public static double g(double x) { return 4 * h(x); }public static double h(double x) { return x * x + k(x) - 1; }public static double k(double x) { return 2 * (x + 1); }Without actually compiling and running
Enhance the intName method so that it works correctly for negative values and zero. Caution: Make sure the improved method doesn’t print 20 as "twenty zero".
Write a methodpublic static String middle(String str)that returns a string containing the middle character in str if the length of str is odd,or the two middle characters if the length is even. For example, middle("middle") returns "dd".
True or false?a. A method has exactly one return statement.b. A method has at least one return statement.c. A method has at most one return value.d. A method with return value void never has a return statement.e. When executing a return statement, the method exits immediately.f. A method with
Enhance the intName method so that it works correctly for values < 1,000,000,000.
Write the following methods.a. int firstDigit(int n), returning the first digit of the argumentb. int lastDigit(int n), returning the last digit of the argumentc. int digits(int n), returning the number of digits of the argumentFor example, firstDigit(1729) is 1, lastDigit(1729) is 9, and
Give examples of the following methods from the Java library.a. A method with a double argument and a double return valueb. A method with two double arguments and a double return valuec. A method with a String argument and a double return valued. A method with no arguments and a double return value
Write a methodpublic static double readDouble(String prompt)that displays the prompt string, followed by a space, reads a floating-point number in, and returns it. Here is a typical usage: salary = readDouble("Please enter your salary:");percentageRaise = readDouble("What percentage raise would you
Write the following methods and provide a program to test them.a. boolean allTheSame(double x, double y, double z), returning true if the arguments are all the sameb. boolean allDifferent(double x, double y, double z), returning true if the arguments are all differentc. boolean sorted(double x,
Write method headers for methods with the following descriptions.a. Computing the larger of two integersb. Computing the smallest of three floating-point numbersc. Checking whether an integer is a prime number, returning true if it is and false otherwised. Checking whether a string is contained
It is a well-known phenomenon that most people are easily able to read a text whose words have two characters flipped, provided the first and last letter of each word are not changed. For example, I dn’ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn) Write a method String
Write the following methods and provide a program to test them.a. double smallest(double x, double y, double z), returning the smallest of the argumentsb. double average(double x, double y, double z), returning the average of the arguments
In a travel simulation, Harry will visit one of his friends that are located in three states. He has ten friends in California, three in Nevada, and two in Utah. How do you produce a random number between 1 and 3, denoting the destination state, with a probability that is proportional to the number
Suppose you design an educational game to teach children how to read a clock. How do you generate random values for the hours and minutes?
The nested loopsfor (int i = 1; i <= height; i++){for (int j = 1; j <= width; j++) { System.out.print("*"); }System.out.println();}display a rectangle of a given width and height, such as************Write a single for loop that displays the same rectangle.
Draw a picture of the “four-leaved rose” whose equation in polar coordinates is r = cos(2θ). Let θ go from 0 to 2π in 100 steps. Each time, compute r and then compute the (x, y) coordinates from the polar coordinates by using the formula x = r · cos(θ), y = r · sin(θ)
What are nested loops? Give an example where a nested loop is typically used.
It is easy and fun to draw graphs of curves with the Java graphics library. Simply draw 100 line segments joining the points (x, f(x)) and (x + d, f(x + d)), where x ranges from xmin to xmax and d = (xmax – xmin) ∕ 100. Draw the curve f(x) = 0.00005x3 – 0.03x2 + 4x + 200, where x ranges from
Write a graphical application that draws a spiral, such as the following:
The photo at left shows an electric device called a “transformer”. Transformers are often constructed by wrapping coils of wire around a ferrite core. The figure below illustrates a situation that occurs in various audio devices such as cell phones and music players. In this circuit, a
Write a graphical application that displays a checkerboard with 64 squares, alternating white and black.
Radioactive decay of radioactive materials can be modeled by the equation A = A0e-t (log 2/h), where A is the amount of the material at time t, A0 is the amount at time 0, and h is the half-life. Technetium-99 is a radioisotope that is used in imaging of the brain. It has a half-life of 6 hours.
Write a program to plot the following face.
A simple model for the hull of a ship is given bywhere B is the beam, L is the length, and T is the draft. (Note: There are two values of y for each x and z because the hull is symmetric from starboard to port.)The cross-sectional area at a point x is called the “section” in nautical parlance.
Using the Picture class from Worked Example 4.2, apply a “telescope” effect, turning all pixels black that are outside a circle. The center of the circle should be the image center, and the radius should be 40 percent of the width or height, whichever is smaller. Cay Horstmann.
Projectile flight. Suppose a cannonball is propelled straight into the air with a starting velocity v0. Any calculus book will state that the position of the ball after t secondswhere g = 9.81 m/s2 is the gravitational force of the earth. No calculus textbook ever mentions why someone would want to
Give an example of a for loop where symmetric bounds are more natural. Give an example of a for loop where asymmetric bounds are more natural.
In a predator-prey simulation, you compute the populations of predators and prey, using the following equations:Here, A is the rate at which prey birth exceeds natural death, B is the rate of predation, C is the rate at which predator deaths exceed births without food, and D represents predator
What do the following program segments print? Find the answers by tracing the code, not by using the computer.a. int n = 1;for (int i = 2; i < 5; i++) { n = n + i; }System.out.print(n);b. int i;double n = 1 / 2;for (i = 2; i <= 5; i++) { n = n + 1.0 / i; }System.out.print(i);c. double x =
Credit Card Number Check. The last digit of a credit card number is the check digit, which protects against transcription errors such as an error in a single digit or switching two digits. The following method is used to verify actual credit card numbers but, for simplicity, we will describe it for
Using the Picture class from Worked Example 4.2, write a program that reads in the file names of two pictures and superimposes them. The result is a picture whose width and height are the larger of the widths and heights of both pictures. In the area where both pictures have pixels, average the
What do the following loops print? Work out the answer by tracing the code, not by using the computer.aa. int s = 1;for (int n = 1; n <= 5; n++){s = s + n;System.out.print(s + " ");}b. int s = 1;for (int n = 1; s <= 10; System.out.print(s + " ")){n = n + 2;s = s + n;}c. int s = 1;int n;for (n
You need to control the number of people who can be in an oyster bar at the same time. Groups of people can always leave the bar, but a group cannot enter the bar if they would make the number of people in the bar exceed the maximum of 100 occupants. Write a program that reads the sizes of the
Write a program that reads an integer and displays, using asterisks, a filled diamond of the given side length. For example, if the side length is 4, the program should display を★ ***** ******* *****
Write an application to pre-sell a limited number of cinema tickets. Each buyer can buy as many as 4 tickets. No more than 100 tickets can be sold. Implement a program called Ticket Seller that prompts the user for the desired number of tickets and then displays the number of remaining tickets.
Write a program that reads an integer and displays, using asterisks, a filled and hollow square, placed next to each other. For example if the side length is 5, the program should display ***** ***** ***** * ****** 中 ***** * ***** *****
Rewrite the following do loop into a while loop.int n = in.nextInt();double x = 0;double s;do{s = 1.0 / (1 + n * n);n++;x = x + s;}while (s > 0.01);
Your company has shares of stock it would like to sell when their value exceeds a certain target price. Write a program that reads the target price and then reads the current stock price until it is at least the target price. Your program should use a Scanner to read a sequence of double values
Write a program that prints a multiplication table, like this: 3 4 5 6 4 6 8 10 12 14 16 18 20 9 12 15 18 21 24 27 30 7 8 9 10 1 2 2 3 10 20 30 40 50 60 70 80 90 100
Showing 500 - 600
of 835
1
2
3
4
5
6
7
8
9
Step by Step Answers