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 programming
Big Java, Enhanced Early Objects 7th Edition Cay S Horstmann - Solutions
Write a method:that displays the prompt string, reads an integer, and tests whether it is between the minimum and maxi mum. If not, print an error message and repeat reading the input.Add the method to a class Input.•• public static int readInt( Scanner in, String prompt, String error, int min,
Consider the following algorithm for computing xn for an integer n. If n < 0, xnis 1/x–n. If n is positive and even, then xn = (xn/2 )2. If n is positive and odd, then xn = xn–1 × x. Implement a static method double intPower(double x, int n) that uses this algorithm. Add it to a class called
Improve the Die class of Chapter 6. Turn the generator variable into a static variable so that all dice share a single random number generator.••
Place a BankAccount class in a package whose name is derived from your e-mail address, as described in Section 8.6. Keep the BankAccountTester class in the default package.••
Provide a JUnit test class StudentTest with three test methods, each of which tests a dif ferent method of the Student class in How To 7.1.Data from How to 7.1
Provide JUnit test class TaxReturnTest with three test methods that test different tax situations for the TaxReturn class in Chapter 5.
Write methods:that show the letters H, E, L, O in the graphics window, where the point p is the top-left corner of the letter. Then call the methods to draw the words “HELLO”and “HOLE” on the graphics display. Draw lines and ellipses. Do not use the drawString method. Do not use System.out.
Repeat Exercise • Graphics E8.23 by designing classes LetterH, LetterE, LetterL, and LetterO, each with a constructor that takes a Point2D.Double parameter (the top-left corner) and a method draw(Graphics2D g2).Which solution is more object-oriented?Data from Exercise Graphics E8.23 Write
Add a method ArrayList getStatement() to the BankAccount class that returns a list of all deposits and withdrawals as positive or negative values. Also add a method void clearStatement() that resets the statement.••
•••Declare a class ComboLock that works like the combination lock in a gym locker, as shown here. The lock is constructed with a combina tion—three numbers between 0 and 39. The reset method resets the dial so that it points to 0. The turnLeft and turnRight methods turn the dial by a given
Improve the picture gallery program in Section 8.5 to fill the space more efficiently. Instead of lining up all pictures along the top edge, find the first available space where you can insert a picture (still respecting the gaps).Solve a simpler problem first, lining up the pictures without
In a tile matching game, tiles are arranged on a grid with rows and columns. Two tiles are turned over at a time, and if they match, the player earns a point. If they are adjacent, the player earns an additional point. Implement such a game, using classes Tile, Location (encapsulating a row and
Simulate a car sharing system in which car commuters pick up and drop off passengers at designated stations. Assume that there are 30 such stations, one at every mile along a route. At each station, randomly generate a number of cars and passengers, each of them with a desired target station.Each
In Exercise •• P8.4 , drivers picked up passengers at random. Try improving that scheme. Are drivers better off picking passengers that want to go as far as possible along their route? Is it worth looking at stations along the route to optimize the loading plan? Come up with a solution that
Tabular data are often saved in the CSV (comma-separated values) format. Each table row is stored in a line, and column entries are separated by commas. However, if an entry contains a comma or quotation marks, they enclosed in quotation marks, doubling any quotation marks of the entry. For
For faster sorting of letters, the U.S. Postal Service encourages companies that send large volumes of mail to use a bar code denoting the ZIP code (see Figure 8).The encoding scheme for a five-digit ZIP code is shown in Figure 9. There are full-height frame bars on each side. The five encoded
Implement a program that prints paychecks for a group of student assistants. Deduct federal and Social Security taxes. (You may want to use the tax computation used in Chapter 5. Find out about Social Security taxes on the Internet.) Your program should prompt for the names, hourly wages, and hours
What are all the superclasses of the JFrame class? Consult the Java API documentation or Appendix D.
In Worked Example 9.1,a. What are the subclasses of Employee?b. What are the superclasses of Manager?c. What are the super- and subclasses of SalariedEmployee?d. Which classes override the weeklyPay method of the Employee class?e. Which classes override the setName method of the Employee class?f.
Which of these conditions returns true? Check the Java documentation for the inheritance patterns. Recall that System.out is an object of the PrintStream class. a. System.out instanceof PrintStream b. System.out instanceof OutputStream
Suppose the class Employee is declared as follows:Declare a class Manager that inherits from the class Employee and adds an instance variable bonus for stor ing a salary bonus. Implement the constructors and methods, and supply a test program. public class Employee { } private String name; private
Add a class NumericQuestion to the question hierarchy of Section 9.1. If the response and the expected answer differ by no more than 0.01, accept the response as correct.
Add a class FillInQuestion to the question hierarchy of Section 9.1. Such a question is constructed with a string that contains the answer, surrounded by _ _, for exam ple,"The inventor of Java was _James Gosling_". The question should be displayed as The inventor of Java was _____
Implement a class ChessPiece with method setPosition(String coordinates). The coordinate string identifies the row and column in chess notation, such as "d8" for the initial position of the black queen. Also provide a method ArrayList canMoveTo() that enumerates the valid moves from the current
What does this code fragment print? Why is this an example of polymorphism? Measurable [] data = { new BankAccount (10000), new Country("Belgium", 30510) }; System.out.println (average (data));
The classes Rectangle2D.Double, Ellipse2D.Double, and Line2D.Double implement the Shape interface. The Graphics2D class depends on the Shape interface but not on the rectangle, ellipse, and line classes. Draw a UML diagram denoting these facts.
Suppose r contains a reference to a new Rectangle(5, 10, 20, 30). Which of the following assignments is legal? (Look inside the API documentation to check which interfaces the Rectangle class implements.)a. Rectangle a = r;b. Shape b = r;c. String c = r;d. ActionListener d = r;e. Measurable e =
Classes such as Rectangle2D.Double, Ellipse2D.Double, and Line2D.Double implement the Shape interface. The Shape interface has a method: Rectangle getBounds () that returns a rectangle completely enclosing the shape. Consider the method call: Shape s = . . .; Rectangle r = s.getBounds (); Explain
Suppose you need to process an array of employees to find the average salary. Discuss what you need to do to use the Data. average method in Section 10.1.3 (which processes Measurable objects). What do you need to do to use the second implementation (in Section 10.4)? Which is easier?Data from
What happens if you try to use an array of String objects with the Data average method in Section 10.1.3?Data from section 10.1.3
How can you use the Data average method in Section 10.4 if you want to compute the average length of the strings?Data from section 10.4
What happens if you pass an array of strings and an AreaMeasurer to the Data.average method of Section 10.4?Data from section 10.4
Consider this top-level and inner class. Which variables can the f method access? public class T { private int t; public void m(final int x, int y) { int a; final int b; class C implements I public void f() { { } } } } final int c;
What happens when an inner class tries to access a local variable that assumes more than one value? Try it out and explain your findings.
How would you reorganize the InvestmentViewer1 program of Section 10.7.2 if you needed to make AddInterestListener into a top-level class (that is, not an inner class)?
Can a class be an event source for multiple event types? If so, give an example.
Implement a class Quiz that implements the Measurable interface of Exercise •• E10.1. A quiz has a score and a letter grade (such as B+). Modify the Data class from Section 10.1 to process an array of quizzes. Display the average score and the quiz with the highest score (both letter grade and
A person has a name and a height in centimeters. Use the Data class of Exercise E10.2 to process an array of Person objects. Display the aver age height and the name of the tallest person.Data from Exercise E10.2Implement a class Quiz that implements the Measurable interface of Exercise ••
In Worked Example 10.1, add a default method:that yields an array of the first n values of the sequence.Data from worked example 10.1. default int[] values(int n)
Add a method to the Data class that returns the object with the largest measure, as measured by the supplied measurer: public static Object largest (Object[] objects, Measurer m)
Using a different Measurer object, process a set of Rectangle objects to find the rectangle with the largest perimeter.
Modify the Coin class from Section 8.2.1 to have it implement the Comparable interface.
Repeat Exercise • E10.8 , making the Measurer into an inner class inside the main method.Data from Exercise E10.8 Using a different Measurer object, process a set of Rectangle objects to find the rectangle with the largest perimeter.•
Repeat Exercise • E10.8 , making the Measurer an inner class outside the main method. Data from Exercise E10.8Using a different Measurer object, process a set of Rectangle objects to find the rectangle with the largest perimeter.
Implement a class Bag that stores items represented as strings. Items can be repeated.Supply methods for adding an item, and for counting how many times an item has been added:Your Bag class should store the data in an ArrayList, where Item is an inner class with two instance variables: the name of
Implement a class Grid that stores measurements in a rectangular grid. The grid has a given number of rows and columns, and a description string can be added for any grid location. Supply the following constructor and methods: public Grid (int numRows, int numColumns) public void add (int row, int
Reimplement Exercise •• E10.13 where the grid is unbounded. The constructor has no arguments, and the row and column parameter variables of the add and getDescription methods can be arbitrary integers.Data from Exercise E10.13Implement a class Grid that stores measurements in a rectangular
Write a method randomShape that randomly generates objects implementing the Shape interface in the Java library API: some mixture of rectangles, ellipses, and lines, with random positions. Call it ten times and draw all of them.
Enhance the ButtonViewer program in Section 10.7.1 so that it prints a message “Iwasclicked n times!” whenever the button is clicked. The value n should be incremented with each click.
Enhance the ButtonViewer program so that it has two buttons labeled A and B, each of which prints a message “Button x was clicked!”, where x is A or B.
Implement a ButtonViewer program as in Exercise •• Graphics E10.18 , using only a single listener class.Data from Exercise Graphics E10.18Enhance the ButtonViewer program so that it has two buttons labeled A and B, each of which prints a message “Button x was clicked!”, where x is A or B.
Implement the AddInterestListener in the InvestmentViewer1 program as a regular class (that is, not an inner class). Store a reference to the bank account. Add a constructor to the listener class that sets the reference.
Implement the AddInterestListener in the InvestmentViewer2 program as a regular class (that is, not an inner class). Store references to the bank account and the label in the listener. Add a constructor to the listener class that sets the references.
Reimplement the program in Section 10.7.2, specifying the listener with a lambda expression (as described at the end of Section 10.7.2).
Reimplement the program in Section 10.8, specifying the listener with a lambda expression (as described at the end of Section 10.7.2).Data from 10.8data from 10.7.2
Reimplement the program in Section 10.9, specifying the listener with a lambda expression.Data From Section 10.9: sec09/RectangleFrame.java 1 import java.awt.event.Action Event; 2 import java.awt.event.ActionListener; 3 import javax.swing.JFrame; 4 import javax.swing.Timer; 5 6 /**
Change the RectangleComponent for the animation program in Section 10.9 so that the rectangle bounces off the edges of the component rather than moving outside.Data from section 10.9
Change the RectangleComponent for the mouse listener program in Section 10.10 so that a new rectangle is added to the component whenever the mouse is clicked. Keep an ArrayList and draw all rectangles in the paintComponent method.
Suppose we have a string holding the text of an entire book. If we want to analyze segments of the text, it is inefficient to make substrings. Instead, we should just store a reference to the original text and the starting and ending positions. Design a class Segment that does this, and have it
Your task is to design a general program for managing board games with two players.Your program should be flexible enough to handle games such as tic-tac-toe, chess, or the Game of Nim of Exercise P6.5.Design an interface Game that describes a board game. Think about what your program needs to do.
Write a program that lets users design bar charts with a mouse. When the user clicks inside a bar, the next mouse click extends the length of the bar to the x-coordinate of the mouse click. (If it is at or near 0, the bar is removed.) When the user clicks below the last bar, a new bar is added
Consider the task of writing a program that plays tic-tac-toe against a human opponent.A user interface TicTacToeUI reads the user’s moves and displays the computer’s moves and the board. A class TicTacToeStrategy determines the next move that the computer makes. A class TicTacToeBoard
Consider the task of translating a plain-text book from Project Gutenberg (http://gutenberg.org) to HTML. For example, here is the start of the first chapter of Tol stoy’s Anna Karenina:Chapter 1 Happy families are all alike; every unhappy family is unhappy in its own way.Everything was in
Write a program that demonstrates the growth of a roach population. Start with two roaches and double the number of roaches with each button click.
Design an interface MoveableShape that can be used as a generic mechanism for animating a shape. A moveable shape must have two methods: move and draw. Write a generic AnimationPanel that paints and moves any MoveableShape (or array list of MoveableShape objects). Supply moveable rectangle and car
What happens when you supply the same name for the input and output files to the Total program of Section 11.1? Try it out if you are not sure.
Suppose you wanted to add the total to an existing file instead of writing a new file. Exercise • R11.1 indicates that you cannot simply do this by specifying the same file for input and output. How can you achieve this task? Provide the pseudocode for the solution.Data from exercise
Your input file contains a sequence of numbers, but sometimes a value is not available and is marked as N/A. How can you read the numbers and skip over the markers?
Can the readFile method in Section 11.5 throw a NullPointer Exception? If so, how?
Write a program that reads a file containing rows of numbers. Each row may have a different length, and some may be blank. Print the average of each row, or zero if a row is blank.
Modify the BankAccount class to throw an IllegalArgumentException when the account is constructed with a negative balance, when a negative amount is deposited, or when an amount that is not between 0 and the current balance is withdrawn. Write a test program that causes all three exceptions to
Repeat Exercise • E11.15 , but throw exceptions of three exception types that you provide.Data from Exercise E11.15 Modify the BankAccount class to throw an IllegalArgumentException when the account is constructed with a negative balance, when a negative amount is deposited, or when an amount
Using the mechanism described in Special Topic 11.1, write a program that reads all data from a web page and writes them to a file. Prompt the user for the web page URL and the file.Data from special topic 11.1 Special Topic 11.1 Reading Web Pages You can read the contents of a web page with this
Download the file airports.dat from https://openflights.org/data.html. Write a program that prompts the user for the name of a city and then reads the airport data file, printing the names of all airports in the provided city.
Write a program that reads in a set of coin descriptions from a file. The input file has the format: coinNamel coinValuel coinName2 coinValue2 Add a method void read (Scanner in) throws FileNot FoundException to the Coin class of Section 8.2. Throw an exception if the current line is not properly
Design a class Bank that contains a number of bank accounts. Each account has an account number and a current balance. Add an accountNumber field to the BankAccount class. Store the bank accounts in an array list. Write a readFile method of the Bank class for reading a file with the
Suppose you are asked to implement a program that simulates your favorite social network. List the classes that you would implement.
Consider an enhancement of the quiz application from Chapter 9 such that a course has a number of quizzes and a number of students. Each student can log in (with a user name and password) and take a quiz. The scores are recorded. A teacher can log in, add students and quizzes, and see all scores.
Write CRC cards for the Coin and CashRegister classes described in Section 8.2.Data from section 8.2
Write CRC cards for the Quiz and Question classes in Section 12.2.2.Data from section 12.2.2
Draw a UML diagram for the Quiz, Question, and ChoiceQuestion classes. The Quiz class is described in Section 12.2.2.
Consider the following problem description: Users place coins in a vending machine and select a product by pushing a button. If the inserted coins are sufficient to cover the purchase price of the product, the product is dispensed and change is given. Otherwise, the inserted coins are retumed to
Consider the following problem description: Employees receive their biweekly paychecks. They are paid their hourly rates for each hour worked; however, if they worked more than 40 hours per week, they are paid overtime at 150 percent of their regular wage. What classes should you use to implement a
Consider the following problem description: Customers order products from a store. Invoices are generated to list the items and quantities ordered, payments received, and amounts still due. Products are shipped to the shipping address of the customer, and invoices are sent to the billing address.
Provide a user interface to the invoice program in Section 12.3 that allows a user to enter and print an arbitrary invoice. Do not modify any of the existing classes.
Write a program to design an appointment calendar. An appointment includes the date, starting time, ending time, and a description; for example,Supply a user interface to add appointments, remove canceled appointments, and print out a list of appointments for a particular day. Follow the design
In an “instant runoff” election, voters mark their favorite candidate on the ballot as well as two alternate candidates (in case their first or second choice does not win). When the ballots are counted, the candidate with the least votes is eliminated, and the ballots for that candidate are
To compute the sum of the values in an array, add the first value to the sum of the remaining values, computing recursively. Design a recursive helper method to solve this problem.
How can you write a recursive method public static void sum(int[] a) without needing a helper function? Why is this less efficient?
Outline, but do not implement, a recursive solution for sorting an array of numbers. First sort the subarray without the initial element.
In some cultures, numbers containing the digit 8 are lucky numbers. What is wrong with the follow ing method that tries to test whether a number is lucky? public static boolean isLucky (int number) { } int last Digit number % 10; if (last Digit==8) { return true; } else { return isLucky (number /
Using backtracking, write a program that solves summation puzzles in which each letter should be replaced by a digit, such as send + more = money Your program should find the solution 9567 + 1085 = 10652. Other examples are base + ball = games and kyoto + osaka = tokyo. In a partial solution, some
Using the isPalindrome method from Section 13.2 and a recursive reverse method from Exercise • E13.6, write a program to address the following mathematical hypothesis. It is believed (but not proven) that, given any decimal number, adding the number and its reversal, will eventually reach a
Change the permutations method of Section 13.4 (which computed all permutations at once) to a PermutationIterator (which computes them one at a time).Now we need a way to iterate through the permutations recursively. Consider the string "eat". As before, we’ll generate all permutations that start
Implement an iterator that produces the moves for the Towers of Hanoi puzzle described in Worked Example 13.2. Provide methods hasMoreMoves and nextMove. The nextMove method should yield a string describing the next move. For example, the following code prints all moves needed to move five disks
Using backtracking, write a program to find whether a given word can be spelled with symbols for the chemical elements. For example, brother can be spelled as Br O Th Er, the symbols for bromium, oxygen, thorium, and erbium.
The Koch Snowflake. A snowflake-like shape is recursively defined as follows. Start with an equilateral triangle: Next, increase the size by a factor of three and replace each straight line with four line segments: Repeat the process: Write a program that draws the iterations of the snowflake
In Java, objects are grouped into classes according to their behavior. Would a window object and a water heater object belong to the same class or to different classes?Why?
Some light bulbs use a glowing filament, others use a fluorescent gas. If you consider a light bulb a Java object with an “illuminate” method, would you need to know which kind of bulb it is?
Explain the difference between an object and a class.
Showing 500 - 600
of 791
1
2
3
4
5
6
7
8
Step by Step Answers