2.99 See Answer

Question: Write an application that counts the words

Write an application that counts the words in a String entered by a user. Words are separated by any combination of spaces, periods, commas, semicolons, question marks, exclamation points, or dashes. Figure 7-17 shows a typical execution. Save the file as CountWords.java.


Write an application that counts the words in a String entered by -1


> Create a UsedCarException class that extends Exception; its constructor receives a value for a vehicle identification number (VIN) that is passed to the parent constructor so it can be used in a getMessage() call. Save the class as UsedCarException.java.

> Create a CourseException class that extends the Java Exception class and whose constructor receives a String that holds a college course’s department (for example, CIS), a course number (for example, 101), and a number of credits (for example, 3). Save t

> Write an application that prompts the user to enter an integer and displays its square root. Accept the user’s entry as a String using the nextLine() method. Then try to use the Integer.parseInt() method to convert the String to an integer. If the conver

> Write a program that prompts the user to enter an integer that represents an array size. Java generates a NumberFormatException if the user attempts to enter a noninteger value using nextInt(). Handle this exception by displaying an appropriate error mes

> Write a program that accepts a number of quarts from a user and converts the value to gallons. Include exception-handling capabilities in the program so that while any nonnumeric value is entered, the program continually displays an error message, reprom

> The Double.parseDouble() method requires a String argument, but it fails if the String cannot be converted to a floating-point number. Write an application in which you try accepting a double input from a user and catch a NumberFormatException if one is

> In a “You Do It” section of this chapter, you created a CalculatorDemo program that asked the user to solve an arithmetic problem and provided the Windows system calculator for assistance. Now modify that program to include the following improvements: ❯❯

> Throughout the Case Problems in this course, you have been using an Event class to store data about events for Yummy Catering. Now, create an application that prompts the user for details about eight Event objects, and create a data file that contains ea

> Serendipity Gifts accepts user orders for its products interactively. Users might make the following errors as they enter data: ❯❯ The item number ordered is not numeric, too low (less than 0), or too high (more than 9

> Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Save the file as DataEntryException.java. b. Write a program named GetIDAndAge that continually prompts the user for an integer ID number and an

> Write an application named BadSubscriptCaught in which you declare an array of eight first names. Write a try block in which you prompt the user for an integer and display the name in the requested position. Create a catch block that catches the potentia

> The Talk-A-Lot Cell Phone Company provides phone services for its customers. Create an abstract class named PhoneCall that includes a String field for a phone number and a double field for the price of the call. Also include a constructor that requires a

> Create an abstract class named Book. Include a String field for the Book’s title and a double field for the book’s price. Within the class, include a constructor that requires the book title, and add two get methods—one that returns the title and one tha

> Create a class named Rock that acts as a superclass for rock samples collected and catalogued by a natural history museum. The Rock class contains fields for a number of samples, a description of the type of rock, and the weight of the rock in grams. Inc

> Create a class named Pizza with a String array data field that can hold the names of up to 10 pizza toppings. Also include a field for the price. Include a constructor that takes two parameters: the array of toppings and the number of toppings stored in

> Create a class named BaseballGame that contains data fields for two team names. Include a two-dimensional array that can hold the scores for each of two teams in each inning of the game. The BaseballGame class includes a final int that represents the n

> Create a class named Poem that contains fields for the name of the Poem and the number of lines in it. Include a constructor that requires values for both fields. Also include get methods to retrieve field values. Save the file as Poem.java. b. Create th

> Create a TeeShirt class for Tamjeed’s Tee Shirt Company. Fields include an order number, size, color, and price. Create set methods for the order number, size, and color, and create get methods for all four fields. The price is determined by the size: $2

> In Chapter 9, you created an interactive LessonWithRentalDemo class that obtains data for four rentals from Sunshine Seashore Supplies, including details about the contract number, length of the rental, and equipment type. After data entry, the applicati

> Create a class named Candle for a candle-making business. Include data fields for color, height, and price. Create get methods for all three fields. Create set methods for color and height, but not for price. Instead, when height is set, determine the pr

> Create a record named Inventor that stores two Strings: the name of an inventor and the inventor’s country of origin. Save the file as Inventor.java. b. Create an Invention class with three fields: a String description of the invention, an Inventor objec

> Create an interface called Runner. The interface has an abstract method called run(). Save the file as Runner.java. b. Create classes called Machine, Athlete, and PoliticalCandidate that all implement Runner. The run() method displays a message describin

> Create an abstract class called GeometricFigure. Each figure includes a height, a width, and a String figure type. Include an abstract method to determine the area of the figure. Save the file as GeometricFigure.java. b. Create two subclasses of Geometr

> Create an interface named Turner, with a single method named turn(). Save the file as Turner.java. b. Create a class named Leaf that implements turn() to display Changing colors. Create a class named Page that implements turn() to display Going to the ne

> Create a class named Blanket with fields for a Blanket’s size, color, material, and price. Include a constructor that sets default values for the fields as Twin, white, cotton, and $30.00. Include a set method for each of the first three fields. The meth

> Create an abstract Division class with fields for a company’s division name and account number, and an abstract display() method. Use a constructor in the superclass that requires values for both fields. Save the file as Division.java. b. Create two sub

> Create a class named Horse that contains data fields for the name, color, and birth year. Include get and set methods for these fields. Save the file as Horse.java. b. Create a subclass of Horse named RaceHorse, which contains an additional field that ho

> Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set method for the sale amount, calculate the sales tax as 5 percent

> Create a personal phone directory that contains room for first names and phone numbers for 30 people. Assign names and phone numbers for the first 10 people. Prompt the user for a name, and if the name is found in the list, display the corresponding phon

> In Chapter 9, you created a DinnerEventDemo class that obtains user data for an array of dinner events for Yummy Catering and allows the user to sort the events using various criteria. Now, modify the application so that it becomes immune to user data en

> Write an application that allows a user to enter the names and birthdates of up to 10 friends. Continue to prompt the user for names and birthdates until the user enters the sentinel value ZZZ for a name or has entered 10 names, whichever comes first. Wh

> Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS 210), credit hours (for example, 3), and a letter grade (for example, A). Include get and set methods for each field. Save the file as CollegeCourse.java. b. Cre

> Create a class named Salesperson. Data fields for Salesperson include an integer ID number and a double annual sales amount. Methods include a constructor that requires values for both data fields, as well as get and set methods for each of the data fiel

> Create an application that prompts a user for 10 integers and stores them in an array. The application should call five methods that in turn (1) display all the integers, (2) display all the integers in reverse order, (3) display the sum of the intege

> Write an application for Chapa’s Car Care Shop that shows a user a list of available services: oil change, tire rotation, battery check, or brake inspection. Allow the user to enter a string that corresponds to one of the options, and display the option

> Allow a user to enter any number of double values up to 15. The user should enter 99999 to quit entering numbers. Display an error message if the user quits without entering any numbers; otherwise, display a count of the numbers entered, the arithmetic a

> Create a program with an enumeration that contains the names of the eight planets in our solar system. Prompt the user for a planet name and use the ordinal() method to display the planet’s position. Save the file as Planets.java.

> Create an application that contains an enumeration that represents the days of the week. Display a list of the days, and then prompt the user for a day. Display business hours for the chosen day. Assume that the business is open from 11 to 5 on Sunday, 9

> Write an application that stores at least five different college courses (such as CIS101), the time it first meets in the week (such as Mon 9 am), and the instructor (such as Khan) in a two-dimensional array. Allow the user to enter a course name and dis

> Radio station KJAVA wants a class to keep track of recordings it plays. Create a class named Recording that contains fields to hold methods for setting and getting a Recording’s title, artist, and playing time in seconds. Save the file as Recording.java.

> In Chapter 8, you created a Rental class for Sunshine Seashore Supplies. Now extend the class to create a LessonWithRental class. In the extended class, include a new boolean field that indicates whether a lesson is required or optional for the type of e

> The mean of a list of numbers is its arithmetic average. The median of a list is its middle value when the values are placed in order. For example, if an ordered list contains 1, 2, 3, 4, 5, 6, 10, 11, and 12, then the mean is 6, and their median is 5. W

> Write an application containing an array of 15 String values. Accept any number of Strings up to 15 from a user, and display them in ascending order. Save the file as StringSort.java.

> Each week, the Pickering Trucking Company randomly selects one of its 30 employees to take a drug test. Write an application that determines which employee will be selected each week for the next 52 weeks. Use the Math.random() function explained in Appe

> Write an application that stores nine integers in an array named numbers. Display the integers from first to last, and then display the integers from last to first. Save the file as NineInts.java.

> Write an application that accepts up to 20 Strings, or fewer if the user enters a terminating value. Store each String in one of two lists—one list for short Strings that are 10 characters or fewer and another list for long Strings that are 11 characters

> Write an application that accepts a word from a user and converts it to Pig Latin. If a word starts with a consonant, the Pig Latin version removes all consonants from the beginning of the word and places them at the end, followed by ay. For example, cri

> Three-letter acronyms are common in the business world. For example, in Java you use the IDE (Integrated Development Environment) in the JDK (Java Development Kit) to write programs used by the JVM (Java Virtual Machine) that you might send over a LAN (l

> Write an application that accepts three Strings from the user and, without regard to case, appropriately displays a message that indicates whether the Strings were entered in alphabetical order. Save the file as Alphabetize.java. b. Write an application

> Write an application that prompts the user for a password that contains at least two uppercase letters, at least three lowercase letters, and at least one digit. Continually reprompt the user until a valid password is entered. Display a message indicatin

> Create a Card class that holds a suit and value for each Card object. Save the file as Card.java. b. Create an abstract CardGame class similar to the one described in this chapter. The class contains a virtual deck of 52 playing cards that uses a Card cl

> Create a program that contains a String that holds your favorite inspirational quote and display the total number of spaces contained in the String. Save the file as CountSpaces.java. b. Write an application that counts the total number of spaces contain

> Write an application that prompts the user for three first names and concatenates them in every possible two name combination so that new parents can easily compare them to find the most pleasing baby name. Save the file as BabyNameComparison.java.

> Create a TaxReturn class with fields that hold a taxpayer’s Social Security number, last name, first name, street address, city, state, zip code, annual income, marital status, and tax liability. Include a constructor that requires argu

> Write an application that determines whether a phrase entered by the user is a palindrome. A palindrome is a phrase that reads the same backward and forward without regarding capitalization or punctuation. For example, Dot saw I was Tod, Was it a car or

> Write a program that inserts parentheses, a space, and a dash into a String of 10 user-entered numbers to format it as a phone number. For example, 5153458912 becomes (515)345-8912. If the user does not enter exactly 10 digits, display an error message.

> Modify the CharacterInfo class shown in Figure 7-3 so that the tested character is retrieved from user input. Save the file as InputCharacterInfo.java.

> The Freemont Automobile Factory has set a goal that each worker will eventually produce 10,000 parts per month. The company has discovered that the longer a worker has been on the job, the more parts the worker can produce. Write an application that prom

> Write an application that allows a user to enter any number of student quiz scores until the user enters a sentinel 99. If the score entered is less than 0 or greater than 10, display an appropriate message and do not use the score. After all the scores

> Accept a digit from the user, then display a seven-line triangle pattern that uses the digit. Figure 6-33 shows a typical execution. The program can contain no more than three output statements. Save the file as TriangleWithLoops.java.

> Which of the following can be specified by using a parameter in one or more versions of the JTextField constructor? a. the initial text in the field b. requiring that the value entered be nonnumeric c. requiring that the entered value be numeric d. makin

> In previous chapters, you developed classes that hold rental contract information for Sunshine Seashore Supplies. Now modify the Rental class to include an integer field that holds an equipment type. Add a final String array that holds names of the types

> A JFrame is a descendant of each of the following classes except the _________________ class. a. Component b. Container c. Jar d. Window 2. Unlike a Window, a JFrame _________________. a. has a title bar and border b. can be made visible c. can have des

> The method that can be used to sort an ArrayList is _________________. a. Collections.sort() b. ArrayList.sort() c. List.sort() d. Sorting.sort() 12. All of the following classes contain a built-in compareTo() method except _________________. a. Integer

> In programming, a(n) _________________ is a group of objects that can be operated on together. a. collision b. anthology c. assemblage d. collection 2. A difference between a collection and an array is that a collection _________________. a. can hold re

> In a recursive method, there typically are _________________. a. more base cases than if statements b. more recursive cases than base cases c. more base cases than while loops d. more base cases than recursive cases 12. The case in a recursive method th

> Recursion is a(n) _________________. a. problem-solving method b. iterative technique c. object-oriented technique d. set of standards 2. Recursion is often used when a problem’s solution relies on a _________________. a. more complicated solution to th

> If you fail to close an output file, _________________. a. there are usually no serious consequences b. you might lose access to the written data c. Java will close it for you automatically d. it becomes an input file 12. Which of the following is true

> Which of the following statements is true? a. Volatile storage lasts only a few seconds. b. Volatile storage is lost when a computer loses power. c. Computer disks are volatile storage devices. d. Volatile storage is also known as persistent storage. 2.

> When a try block does not generate an Exception and you have included multiple catch blocks,_________________. a. no catch blocks execute b. only the first catch block executes c. only the first matching catch block executes d. all the catch blocks execu

> In object-oriented programming terminology, an unexpected or error condition is a(n) _________________. a. anomaly b. exception c. deviation d. aberration 2. All Java Exceptions are _________________. a. Errors b. Omissions c. Throwables d. RunTimeExcep

> When a parent class contains a static method, child classes _________________ override it. a. frequently b. seldom c. must d. cannot 12. Abstract classes differ from other classes in that you _________________. a. must not code any methods within them b

> In previous chapters, you developed classes that work with catering event information for Yummy Catering. Now modify the Event class to include an integer field that holds an event type. Add a final String array that holds names of the types of events th

> Employing inheritance reduces errors because _________________. a. subclasses have access to fewer data fields b. subclasses have access to fewer methods c. methods that have been created in the superclass can be copied and pasted into the subclass d. ma

> A parallel array is one that _________________. a. holds values that correspond to those in another array b. holds an even number of values c. is placed adjacent to another array in code d. is placed adjacent to another array in memory 12. When you pass

> An array is a list of data items that all _________________. a. have the same type b. have different names c. are integers d. are null 2. When you declare an array, _________________. a. you always reserve memory for it in the same statement b. you migh

> If String movie = new String("Finding Dory");, the value of movie.indexOf('i') is _________________. a. true b. false c. 1 d. 2 12. The String class replace() method replaces _________________. a. a String with a character b. one String with another Str

> A sequence of characters enclosed within double quotation marks is a _________________. a. literal string b. symbolic string c. prompt d. command 2. To create a String object, you can use the keyword _________________ before the constructor call, but yo

> 11. If m = 9, then after n = m++, the value of n is ____________. a. 8 b. 9 c. 10 d. 11 12. If j = 5 and k = 6, then the value of j++ == k is ____________. a. 5 b. 6 c. true d. false 13. You must always include ____________ in a for loop’s parentheses.

> 1. A structure that allows repeated execution of a block of statements is a ____________. a. cycle b. ring c. loop d. band 2. A loop that never ends is a(n) ____________ loop. a. infinite b. iterative c. structured d. illegal 3. To construct a loop tha

> The operator that combines two conditions into a single Boolean value that is true only when both of the conditions are true is ____________. a. $$ b. && c. || d. !! 12. The operator that combines two conditions into a single Boolean value that is true

> The logical structure in which one instruction occurs after another with no branching is a ____________. a. sequence b. selection c. loop d. case 2. Which of the following is typically used in a flowchart to indicate a decision? a. square b. rectangle c

> Sunshine Seashore Supplies rents beach equipment to tourists. In previous chapters, you developed a Rental class that holds equipment rental information and an application that tests the methods using three objects of the class. Now create a RentalDemo c

> a. Sunshine Seashore Supplies rents beach equipment to tourists. In previous chapters, you have developed a Rental class that holds equipment rental information. Now modify the Rental class as follows: ❯❯ Modify the method that sets the contract number i

> Create a Die class from which you can instantiate an object containing a random value from 1 through 6. Save the class as Die.java. Write an application that randomly “throws” two dice and displays their values. Determine whether the two dice are the sam

> Design a Card class that contains a character data field to hold a suit (s for spades, h for hearts, d for diamonds, or c for clubs) and an integer data field for a value from 1 to 13. Include a setValue() method that does not allow a Card’s value to be

> Create a lottery game application. Generate three random numbers (see Appendix D for help in doing so), each between 0 and 9. Allow the user to guess three numbers. Compare each of the user’s guesses to the three random numbers and display a message that

> Create a class called RandomGuess2 that contains a game in which a player guesses a random number. (See Appendix D for help with creating a random number.) Allow a player to enter a guess, and then display a message indicating whether the player’s guess

> Create a game called Last Man Standing in which the objective is to select the last remaining JCheckBox. The game contains 10 JCheckBoxes. The player can choose one, two, or three boxes, and then click a JButton to indicate the turn is complete. The comp

> Create a lottery game that uses check boxes. For this game, generate six random numbers, each between 0 and 30 inclusive. Allow the user to choose six check boxes to play the game. (Do not allow the user to choose more than six boxes.) After the player h

> Create a quiz game that displays, in turn, five questions about any topic of your choice. All five questions should have the same three possible multiple-choice answers. For example, you might ask trivia questions about U.S. states for which the correct

> In the children’s game Out of Order, the user is presented with a series of values—for example, A, B, C, E, D, F—and is asked to identify the first item in the list that is out of order. Write a program that stores lists of letters, numbers, and words wi

> Tower of Hanoi is a pyramid puzzle that uses three rods and a number of disks that have different diameters. The disks can slide onto any rod. The puzzle starts with the disks on the first rod, stacked from the smallest at the top to the largest on the b

> Scrabble and Words with Friends are games in which players score points by placing letters on a game board divided into squares. After the first word is placed on the board, subsequent plays must form words that intersect with other letters already in pl

> Yummy Catering provides meals for parties and special events. In previous chapters, you developed a class named Event that holds catering event information. Now create an EventDemo application to do the following: ❯❯ Create three Event objects. ❯❯ Contin

> Use a text editor to create a comma-delimited file of user IDs and passwords. Save the file as GamePlayers.txt. b. Revise any one of the games you have created throughout this course to use the file GamePlayers.txt. Require the user to enter a correct ID

> Create a multiple-choice quiz on any topic. Include at least 10 questions. Store the player’s highest score from any previous game in a file, and display the previous high score at the start of each new game. (The first time you play the game, the previo

> In several Game Zone assignments earlier in this course, you created games similar to Hangman in which the user guesses a secret phrase by selecting a series of letters. These versions had limited appeal because each contained only a few possible phrases

> Create a class that contains an array of 10 multiple-choice questions to which the user is required to respond with an A, B, or C. Display an error message if the user enters a character other than A, B, or C. If the user enters nothing—that is, if the u

> Create an application that generates a random integer for a player to guess. When the player’s guess is not entered as an integer, catch the Exception that is thrown and allow the player to try again. When the guess is an integer that is too high or too

2.99

See Answer