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 an introduction to problem solving and progra
Java An Introduction To Problem Solving And Programming 8th Edition Walter Savitch - Solutions
Write an exception class that is appropriate for indicating that a time entered by a user is not valid. The time will be in the format hour:minute followed by “am” or “pm.”
Write a program that uses the class Calculator in Listing 9.12 to create a more powerful calculator. This calculator will allow you to save one result in memory and call the result back. The commands the calculator takes are e for endc for clear; sets result to zerom for save in memory; sets
Write a program that allows the user to compute the remainder after the division of two integer values. The remainder of x/y is x%y. Catch any exception thrown and allow the user to enter new values.
Write a program that converts a time from 24-hour notation to 12-hour notation. The following is a sample interaction between the user and the program:Enter time in 24-hour notation:13:07That is the same as1:07 PMAgain? (y/n)yEnter time in 24-hour notation:10:15That is the same as10:15 AMAgain?
Define DiscountPolicy as an interface instead of the abstract class described in Exercise 10.Exercise 10.Create an abstract class DiscountPolicy. It should have a single abstract method computeDiscount that will return the discount for the purchase of a given number of a single item. The method has
Derive a class CombinedDiscount from DiscountPolicy, as described in Exercise 10. It should have a constructor that has two parameters of type DiscountPolicy. It should define the method computeDiscount to return the maximum value returned by computeDiscount for each of its two private discount
Derive a class BuyNItemsGetOneFree from DiscountPolicy, as described in Exercise 10. The class should have a constructor that has a single parameter n. In addition, the class should define the method computeDiscount so that every nth item is free. For example, the following table gives the discount
Create an abstract class DiscountPolicy. It should have a single abstract method computeDiscount that will return the discount for the purchase of a given number of a single item. The method has two parameters, count and itemCost.
Derive a class BulkDiscount from DiscountPolicy, as described in the previous exercise. It should have a constructor that has two parameters, minimum and percent. It should define the method computeDiscount so that if the quantity purchased of an item is more than minimum, the discount is percent
Create a JavaFX application that will draw a spiral using line segments. The equations for the points on a spiral are:You should draw 150 points. Start θ at 0 and increase it by 0.1 for each new point. Let k be 15. Set the size of the window to 500 by 500. x = 250 + kO sin 0 y = 250 + kO sin e
Derive a class RegularPay from PayCalculator, as described in the previous exercise. It should have a constructor that has a parameter for the pay rate. It should not override any of the methods. Then derive a class HazardPay from PayCalculator that overrides the computePay method. The new method
Create a JavaFX application that acts as a simple calculator. Create buttons for digits 0-9 and a text field that concatenates digits for the current number as the buttons are clicked. Add additional buttons for operators +, −, *, and /. Add a final button for = that calculates the previously
Create an abstract class PayCalculator that has an attribute payRate given in dollars per hour. The class should also have a method computePay(hours) that returns the pay for a given amount of time.
Create a JavaFX application that uses a TextField to get a message and encode or decode it using the classes described in Programming Project 5. Use buttons to control the kind of cipher used and to specify whether to encode or decode the message. Also use a TextField to get the number used in the
Derive a class ExaggeratingKid from SchoolKid, as described in the previous exercise. The new class should override the accessor method for the age, reporting the actual age plus 2. It also should override the accessor for the greeting, returning the child’s greeting concatenated with the words
Modify the Student class in Listing 8.2 so that it implements the comparable interface. Define the compareTo method to order Student objects based on the value in studentNumber. In a main method create an array of at least five Student objects, sort them using Arrays.sort, and output the students.
For this Programming Project, start with implementations of the Person, Student, and Undergraduate classes as depicted in Figure 8.4 and the polymorphism demo in Listing 8.6. Define the Employee, Faculty, and Staff classes as depicted in Figure 8.2. The Employee class should have instance variables
Create an interface MessageDecoder that has a single abstract method decode(cipherText), where cipherText is the message to be decoded. The method will return the decoded message. Modify the classes SubstitutionCipher and ShuffleCipher, as described in Exercises 16 and 17, so that they implement
Create a class SchoolKid that is the base class for children at a school. It should have attributes for the child’s name and age, the name of the child’s teacher, and a greeting. It should have appropriate accessor and mutator methods for each of the attributes.
Create the classes RightTriangle and Rectangle, each of which is derived from the abstract class ShapeBase in Listing 8.19. Then derive a class Square from the class Rectangle. Each of these three derived classes will have two additional methods to calculate area and circumference, as well as the
Create a class Square derived from DrawableShape, as described in the previous exercise. A Square object should know the length of its sides. The class should have an accessor method and a mutator method for this length. It should also have methods for computing the area and perimeter of the
Suppose we want to implement a drawing program that creates various shapes using keyboard characters. Implement an abstract base class DrawableShape that knows the center (two integer values) and the color (a string) of the object. Give appropriate accessor methods for the attributes. You should
Draw a hierarchy for the components you might find in a graphical user interface. Note that some components can trigger actions. Some components may have graphics associated with them. Some components can hold other components.
Implement your base class for the hierarchy from the previous exercise.Previous exercise.Consider a program that will keep track of the items in a school’s library. Draw a class hierarchy, including a base class, for the different kinds of items. Be sure to also consider items that cannot be
Define a class called Diamond that is derived from either the class ShapeBasics (Listing 8.12) or the abstract class ShapeBase (Listing 8.19). A diamond has the same sort of top half as a Triangle object, and its bottom half is an inverted version of its top half. Define a utility class having
Write a static method blur(double[][]picture) that you could use on a part of a picture file to obscure a detail such as a person’s face or a license plate number. This method computes the weighted averages of the values in picture and returns them in a new twodimensional array. To find a
Write a static method findFigure(picture,threshold), where picture is a twodimensional array of double values. The method should return a new two-dimensional array whose elements are either 0.0 or 1.0. Each 1.0 in this new array indicates that the corresponding value in picture exceeds threshold
Write a sequential search of an array of integers, assuming that the array is sorted into ascending order. Consider an array that contains the four integers 2, 4, 6, and 8. How can you tell that 5 is not in the array without comparing 5 to every integer in the array?
Your application won’t actually function as a calculator at this point. You are just designing the interface.
Revise the class TimeBook in Listing 7.14 to use an enumeration for the days of the week instead of named constants.Listing 7.14 Class that records the t ime worked by each of a company's employees during one five-day week. A sample application is in the main method. */ public class TimeBook {
Create a JavaFX application to create the interface for a calculator. Use a BorderPane in the stage with a TextField at the top. The text field would be used to store the number being entered in the calculator as digits are entered. Create buttons for digits 0–9 in a GridPane in the center of the
Revise the method selectionSort that appears in Listing 7.10 so that it calls the method described in the previous exercise.Listing 7.10/**Class for sorting an array of base type int from smallest to largest.*/public class ArraySorter{/**Precondition: Every element in anArray has a value.Action:
Do Programming Project 15 except use a class named Player to store a player’s name and score. Use a single array of type Player. Be sure to include a constructor with this class that sets the name and score.Programming Project 15Write a program that manages a list of up to 10 players and their
Overload the method selectionSort in Listing 7.10 so that it sorts an array whose indices range from first to last, where 0 ≤ first ≤ last, and last is less than the length of the array.Listing 7.10/**Class for sorting an array of base type int from smallest to largest.*/public class
Write a program that manages a list of up to 10 players and their high scores in the computer’s memory. Use two arrays to manage the list. One array should store the player’s name and the other array should store the player’s high score. Use the index of the arrays to correlate the name with
Write a static method for selection sort that will sort an array of characters.
Practice Program 5.4 asked you to define a Trivia class that contained strings representing a trivia question and answer to that question. Add an integer for the number of points that the question is worth if the player gets the question right. Create constructor, accessor, and mutator methods. Use
Revise the class OneWayNoRepeatsList, as given in Listing 7.9, so that it allocates an extra element in the array entry and ignores entry[0], as suggested earlier near the end of the section entitled “More About Array Indices.”Listing 7.9 /** An object of this class is a special kind of list of
Practice Program 2 used two arrays to implement a simple phone book. A more scalable solution is to make an array of an object that stores the name and corresponding phone number. Modify the program to use a single array of an object. The output should remain the same.
Write a method beyondLastEntry(position) for the class OneWayNo-RepeatsList, as given in Listing 7.9, that returns true when position is beyond the last entry on the list.Listing 7.9 /** An object of this class is a special kind of list of strings. You can write the list only from beginning to end.
Create a GUI application that draws the following picture of a magic wand, using polygons and polylines:
Create a class Polynomial that is used to evaluate a polynomial function of x:The coefficients a are floating-point numbers, the exponents of x are integers, and the largest exponent n—called the degree of the polynomial—is greater than or equal to 0. The class has the attributesdegree—the
Sudoku is a popular logic puzzle that uses a 9 by 9 array of squares that are organized into 3 by 3 subarrays. The puzzle solver must fill in the squares with the digits 1 to 9 such that no digit is repeated in any row, any column, or any of the nine 3 by 3 subgroups of squares. Initially, some
Suppose that we are selling boxes of candy for a fund-raiser. We have five kinds of candy to sell: Mints, Chocolates with Nuts, Chewy Chocolates, Dark Chocolate Creams, and Sugar-Free Suckers. We will record a customer’s order as an array of five integers, representing the number of boxes of each
ELIZA was a program written in 1966 that parodied a psychotherapist session. The user typed sentences and the program used those words to compose a question.Create a simple GUI application based on this idea. The program will use a label to hold the program’s question, a text field into which the
Write a static method remove(int v,int[] in) that will return a new array of the integers in the given array, but with the value v removed. For example, if v is 3 and in contains 0, 1, 3, 2, 3, 0, 3, and 1, the method will return an array containing 0, 1, 2, 0, and 1.
Write a GUI application that displays a picture of a pine tree formed by drawing a triangle on top of a small rectangle that makes up the visible trunk. The tree should be green and have a gray trunk.
Write a static method removeDuplicates(Character[] in) that returns a new array of the characters in the given array, but without any duplicate characters. Always keep the first copy of the character and remove subsequent ones. For example, if in contains b, d, a, b, f, a, g, a, a, and f, the
Traditional password entry schemes are susceptible to “shoulder surfing” in which an attacker watches an unsuspecting user enter his or her password or PIN number and uses it later to gain access to the account. One way to combat this problem is with a randomized challengeresponse system. In
Write a static method isStrictlyIncreasing(double[] in) that returns true if each value in the given array is greater than the value before it, or false otherwise.
Define the following methods for the class Ledger, as described in the previous exercise:getAverageSale()—returns the average value of all the salesgetCountAbove(v)—returns the number of sales that exceeded v in valuePrevious exercise:Create a class Ledger that will record the sales for a
Repeat Programming Project 10 from Chapter 5 but use an array to store the movie ratings instead of separate variables. All changes should be internal to the class, so the main method to test the class should run identically with either the old Movie class or the new Movie class using
Define a class called TicTacToe. An object of type TicTacToe is a single game of tic-tactoe. Store the game board as a single two-dimensional array of base type char that has three rows and three columns. Include methods to add a move, to display the board, to tell whose turn it is (X or O), to
Create a class Ledger that will record the sales for a store. It will have the attributes sale—an array of double values that are the amounts of all sales salesMade—the number of sales so far maxSales—the maximum number of sales that can be recorded and the following
The class TimeBook in Listing 7.14 is not really finished. Complete the definition of this class in the way described in the text. In particular, be sure to add a default constructor, as well as set and get methods that change or retrieve each of the instance variables and each indexed variable of
Write a program in a class CharacterFrequency that counts the number of times a digit appears in a telephone number. Your program should create an array of size 10 that will hold the count for each digit from 0 to 9. Read a telephone number from the keyboard as a string. Examine each character in
Add a method insertionSort to the class ArraySorter, as given in Listing 7.10, that performs an insertion sort of an array. To simplify this project, our insertion sort algorithm will use an additional array. It copies elements from the original given array to this other array, inserting each
Write a program in a class FlowerCounter that computes the cost of flowers sold at a flower stand. Five kinds of flowers—petunia, pansy, rose, violet, and carnation—are stocked and cost, respectively, 50¢, 75¢, $1.50, 50¢, and 80¢ per flower. Create an array of strings that holds the names
Add a method bubbleSort to the class ArraySorter, as given in Listing 7.10, that performs a bubble sort of an array. The bubble sort algorithm examines all adjacent pairs of elements in the array from the beginning to the end and interchanges any two elements that are out of order. Each interchange
Write a program in a class CountPoor that counts the number of families that are considered poor. Write and use a class Family that has the attributesincome—a double value that is the income for the familysize—the number of people in the familyand the following methods:Family(income, size)—a
A palindrome is a word or phrase that reads the same forward and backward, ignoring blanks and considering uppercase and lowercase versions of the same letter to be equal. For example, the following are palindromes:warts n strawradarAble was I ere I saw ElbatacocatWrite a program that will accept a
Write a program in a class CountFamiles that counts the number of families whose income is below a certain value. Read an integer k from the keyboard and then create an array of double values of size k. Read k values representing family income from the keyboard and place them into the array. Find
Write a program that will read a line of text that ends with a period, which serves as a sentinel value. Display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text. Use an array of base type int of length 26,
Write a program in a class NumberAboveAverage that counts the number of days that the temperature is above average. Read ten temperatures from the keyboard and place them in an array. Compute the average temperature and then count and display the number of days on which the temperature was above
Write a program that plays a simplified dice version of blackjack. Instead of selecting from a deck of cards a 14-sided die is rolled to represent a card. The rules of the game for one round, as played against the house, are as follows:a. A roll randomly selects from the values 2–10 or Jack,
Create a program that tests the class Android described in the previous exercise.Previous exercise.Create a class Android whose objects have unique data. The class has the following attributes:tag—a static integer that begins at 1 and changes each time an instance is createdname—a string that
Create a JavaFX application that displays a button with the text “Button 1”. Underneath the button add a label with the text “Label 1”. Repeat with and additional “Button 2” and “Label 2”. Add an image icon of your choice to the first button and the first label.
Repeat Programming Project 10 from Chapter 5, but include constructors.Programming Project 10Consider a class Movie that contains information about a movie. The class has the following attributes:The movie nameThe MPAA rating (e.g., G, PG, PG-13, R)The number of people who have rated this movie as
Write a program that will record the votes for one of two candidates by using the class VoteRecorder, which you will design and create. Vote Recorder will have static variables to keep track of the total votes for candidates and instance variables to keep track of the votes made by a single person.
Create a program that tests the class Merlin described in the previous exercise. Use the toString method to verify that a unique instance has been created.Previous exercise.Sometimes we would like a class that has just a single unique instance. Create a class Merlin that has one attribute,
Sometimes we would like a class that has just a single unique instance. Create a class Merlin that has one attribute, theWizard, which is static and of type Merlin. The class has only one constructor and two methods, as follows:Merlin—a private constructor. Only this class can invoke this
Write and fully test a class that represents rational numbers. A rational number can be represented as the ratio of two integer values, a and b, where b is not zero. The class has attributes for the numerator and denominator of this ratio. The ratio should always be stored in its simplest form.
Write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades. Define a private instance variable to hold a boolean value that is true if the grade is passing. Also, define a constructor that initializes this instance variable, an accessor method
Write a new class TruncatedDollarFormat that is the same as the class DollarFormat from Listing 6.14, except that it truncates rather than rounds to obtain two digits after the decimal point. When truncating, all digits after the first two are discarded, so 1.229 becomes 1.22, not 1.23. Repeat
Consider a class ScienceFairProjectRating that will be used to help judge a science fair project. It will use the class RatingScore described in the previous exercise. The attributes for the new class areThe name of the projectA unique identification string for the projectThe name of the personA
Consider a class that could be used to play a game of hangman. The class has the following attributes:The secret word.The disguised word, in which each unknown letter in the secret word is replaced with a question mark (?). For example, if the secret word is abracadabra and the letters a, b, and e
Create a class that will bundle together several static methods for tax computations. This class should not have a constructor. Its attributes arebasicRate—the basic tax rate as a static double variable that starts at 4 percentluxuryRate—the luxury tax rate as a static double variable that
Define a utility class for displaying values of type double. Call the class DoubleOut. Include all the methods from the class DollarFormat in Listing 6.14, all the methods from the class OutputFormat of Self-Test Question 30, and a method called scienceWrite that displays a value of type double
Consider a class Movie that contains information about a movie. The class has the following attributes:The movie nameThe MPAA rating (e.g., G, PG, PG-13, R)The number of people who have rated this movie as a 1 (Terrible)The number of people who have rated this movie as a 2 (Bad)The number of people
Repeat Programming Project 18 from Chapter 4, but use a method that displays a circular disk as a subtask.Programming Project 18What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?int product = 1;int max = 20;for (int
Create a JavaFX application that displays something like the following picture. You should have methods for drawing a monkey face and a hand. Hear no evil See no evil Speak no evil
Do Programming Project 17 from Chapter 4, the Edoc calculator, except write a method that takes the number of candy, Edoc, and Margorp as input parameters and returns the amount of experience that can be earned. Modify your program to give advice to the player using the following rules:Catching an
Consider a class RatingScore that represents a numeric rating for something such as a movie. Its attributes areA description of what is being ratedThe maximum possible ratingThe ratingIt will have methods toGet the rating from a userReturn the maximum rating possibleReturn the ratingReturn a string
Consider a class BasketballGame that represents the state of a basketball game. Its attributes areThe name of the first teamThe name of the second teamThe score of the first teamThe score of the second teamThe status of the game (finished or in progress)BasketballGame has methods toRecord one point
Write a program to answer questions like the following: Suppose the species Klingon ox has a population of 100 and a growth rate of 15 percent, and it lives in an area of 1500 square miles. How long would it take for the population density to exceed 1 per square mile? Use the class Species in
Write a program that uses the Purchase class in Listing 5.13 to set the following prices:Oranges: 10 for $2.99Eggs: 12 for $1.69Apples: 3 for $1.00Watermelons: $4.39 eachBagels: 6 for $3.50Then calculate the cost of each of the following five items and the total bill:2 dozen oranges3 dozen eggs20
Repeat Exercise 1 for a collection of coins instead of a credit card.Exercise 1Design a class to represent a credit card. Think about the attributes of a credit card; that is, what data is on the card? What behaviors might be reasonable for a credit card? Use the answers to these questions to write
Create a class that represents a grade distribution for a given course. Write methods to perform the following tasks:Set the number of each of the letter grades A, B, C, D, and F.Read the number of each of the letter grades A, B, C, D, and F.Return the total number of grades.Return the percentage
Repeat Exercise 1 for a coin instead of a credit card.Exercise 1Design a class to represent a credit card. Think about the attributes of a credit card; that is, what data is on the card? What behaviors might be reasonable for a credit card? Use the answers to these questions to write a UML class
Add methods to the Person class from Self-Test Question 16 to perform the following tasks:Set the name attribute of a Person object.Set the age attribute of a Person object.Test whether two Person objects are equal (have the same name and age).Test whether two Person objects have the same name.Test
Repeat Exercise 1 for a credit card account instead of a credit card. An account represents the charges and payments made using a credit card.Exercise 1Design a class to represent a credit card. Think about the attributes of a credit card; that is, what data is on the card? What behaviors might be
Write a grading program for an instructor whose course has the following policies: Two quizzes, each graded on the basis of 10 points, are given.One midterm exam and one final exam, each graded on the basis of 100 points, are given.The final exam counts for 50 percent of the grade, the midterm
What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?int sum = 0;intproduct = 1;int max = 20;for (int i = 1; i <= max; i++)sum = sum + i;product = product * i;System.out.println("The sum is " + sum +" and the product
What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?int product = 1;int max = 20;for (int i = 0; i <= max; i++)product = product * i;System.out.println("The product is " + product);
You have an augmented reality game in which you catch Edoc and acquire Edoc candy. You need 12 candies to evolve an Edoc into a Margorp. An evolution earns you back one candy. Each evolution also earns you 500 experience points. An Edoc or Margorp can each be transferred for one Edoc candy. In
Create an applet that draws a pattern of circles whose centers are evenly spaced along a horizontal line. Use six constants to control the pattern: the number of circles to draw, the diameter of the first circle, the x- and y-coordinates of the center of the first circle, the distance between
Write a JavaFx application that displays a series of pictures of a person with arms, legs, and of course a head. Use a happy face for the head. Use ovals for the body, arms, and legs. Draw a sequence of figures that appear one after the other, as in Listing 4.9. Make the figures assume a running
Imagine a program that compresses files by 80 percent and stores them on storage media. Before the compressed file is stored, it must be divided into blocks of 512 bytes each. Develop an algorithm for this program that first reads the number of blocks available on the storage media. Then, in a
Repeat the previous project, but position the centers of the circles on a spiral. The center of each circle will depend on both an angle and a distance from the origin. A constant change in both the angle and the distance will result in a spiral pattern.Previous projectCreate a JavaFx application
Suppose that we want to compute the geometric mean of a list of positive values. To compute the geometric mean of k values, multiply them all together and then compute the kth root of the value. For example, the geometric mean of 2, 5, and 7 is 3√2 × 5 × 7. Use a loop with a sentinel value to
Showing 200 - 300
of 407
1
2
3
4
5
Step by Step Answers