The parseDouble method of class double may be a little too strict in the rules to...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
The parseDouble method of class double may be a little too strict in the rules to convert a string to a double. Consider web pages where a user can enter a value into a form. We may want to allow entry of numbers where the rules are more relaxed. We would like to enable a user to enter a numeric number (a sequence of digits) into the form allowing: Leading or trailing white space (any amout) Embedded single space (but not two spaces in a row) • Optional '+' or '-', but if used must be the first non-white space character ('-' indicates a negative number) • An optional decimal point (but only one decimal point - more than one would be invalid) The optional entry of commas (but only every third position to the left of the decimal point or end of the string if no decimal point is given, and must have at least one digit before a comma) . • . Any other character than digits or those listed as valid above, is an error. Furthermore, not having at least one digit is an error. Write a method prepDouble in class StringUtils which return a String that can be parsed successfully by parseDouble. That is remove allowed white space and commas. If the string does not abide by the specified options then returns an "Invalid number" message as shown below. String "1995" "+3.99" "2,999,888.99" "- 6, 001. 02" "1 1 2 3 +1 2 3 4" "1 11 - 11 11 +"" "4.5.2" "452+" "23, 345, 12.34" "2345, 120" ", 356,120" "2,3456,120" "345.345, 560" "34A9" Value Returned "1995" "3.99" "2999888.99" "-6001.02" "123" "12" "Invalid number - embedded sequence of more than one space" "Invalid number - no value provided" "Invalid number - no value provided" "Invalid number - no value provided" "Invalid number - more that one decimal point" "Invalid number - misplaced + or "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - encountered A" The Main class provided receives a line of input and calls prepDouble. If the return string begins with "Invalid", the returned string is printed. Otherwise, parseDouble is used to convert the return string to a double and the returned doulbe is fromatted and printed with two decimal plactions below the decimal point. Suggested strategy - approach this problem incrementally. That is writing a small section of code and run the tests. Keep writing small sections of code and run the tests after coding each section. This should be the first section of code implemented and tested. Then: • Add code to trim the leading and trailing whitespace. • Add code to check if the input string is empty. If so, return the appropriate invalid number message. • See if input string begins with a '-'. If so set a variable neg to "-". If not set neg to an empty string. Make sure to prepend the neg to the return string when then input passes all checks. • Check If the input string begins with '-' or '+', remove this sign from the beginning of input sting. Recheck if the input string is now empty and if so return the appropriate invalid number message. • Check if the input string has any '+' or '- signs remaining. If so return the appropriate invalid number message. Check if the input string has a sequence of two spaces. If so return the appropriate invalid number message. • Remove all spaces from the input string. Now check for appropriate use of commas and decimal point. To do this first, break the input string into two strings: one containing all characters before a decimal point and another for characters after. If there is no decimal point consider all characters before the decimal point and no characters after. Then: • Check if the after string contains a decimal point. If so, return the appropriate invalid number message. • Check if the after string contains a comma. If so, return the appropriate invalid number message. Check to see if the before string matches a pattern that begins with one, two, or three digits followed by a comma and three digits where the pattern of a comma followed by three digits can be repeated one or more times. If so, remove all commas from the input string. . • Check if the input string has a comma. If so, return the appropriate invalid number message. • Check if the remaining input string contains a character other than digits or one decimal. If a non-digit or decimal point is found, return the appropriate invalid number message. The above can be solved using the String methods: ● contains trim .indexOf ● ● · substring replaceAll length • toCharArray • matches Be careful to code the statements that modify the input string. Keep in mind that Strings are immutable. Methods like trim and replace all do not modify a String. Instead, they return a String. These methods when used should be in the context of an assignment statement where the variable referencing the input string is assign the returned String. File is marked as read only 1 import java.util.Scanner; 2 3 public class Main { 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String line = scnr.nextLine(); String preppedLine StringUtils.prepNumber(line); if (preppedLine.startsWith("Invalid")) { System.out.println(preppedLine); } else { } Current file: Main.java } System.out.printf("%,. 2f", Double.parseDouble(preppedLine)); 1234567 00 1 public class StringUtils { // Add your code here 7} 8 Current file: StringUtils.java Load default template.. The parseDouble method of class double may be a little too strict in the rules to convert a string to a double. Consider web pages where a user can enter a value into a form. We may want to allow entry of numbers where the rules are more relaxed. We would like to enable a user to enter a numeric number (a sequence of digits) into the form allowing: Leading or trailing white space (any amout) Embedded single space (but not two spaces in a row) • Optional '+' or '-', but if used must be the first non-white space character ('-' indicates a negative number) • An optional decimal point (but only one decimal point - more than one would be invalid) The optional entry of commas (but only every third position to the left of the decimal point or end of the string if no decimal point is given, and must have at least one digit before a comma) . • . Any other character than digits or those listed as valid above, is an error. Furthermore, not having at least one digit is an error. Write a method prepDouble in class StringUtils which return a String that can be parsed successfully by parseDouble. That is remove allowed white space and commas. If the string does not abide by the specified options then returns an "Invalid number" message as shown below. String "1995" "+3.99" "2,999,888.99" "- 6, 001. 02" "1 1 2 3 +1 2 3 4" "1 11 - 11 11 +"" "4.5.2" "452+" "23, 345, 12.34" "2345, 120" ", 356,120" "2,3456,120" "345.345, 560" "34A9" Value Returned "1995" "3.99" "2999888.99" "-6001.02" "123" "12" "Invalid number - embedded sequence of more than one space" "Invalid number - no value provided" "Invalid number - no value provided" "Invalid number - no value provided" "Invalid number - more that one decimal point" "Invalid number - misplaced + or "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - misplaced comma" "Invalid number - encountered A" The Main class provided receives a line of input and calls prepDouble. If the return string begins with "Invalid", the returned string is printed. Otherwise, parseDouble is used to convert the return string to a double and the returned doulbe is fromatted and printed with two decimal plactions below the decimal point. Suggested strategy - approach this problem incrementally. That is writing a small section of code and run the tests. Keep writing small sections of code and run the tests after coding each section. This should be the first section of code implemented and tested. Then: • Add code to trim the leading and trailing whitespace. • Add code to check if the input string is empty. If so, return the appropriate invalid number message. • See if input string begins with a '-'. If so set a variable neg to "-". If not set neg to an empty string. Make sure to prepend the neg to the return string when then input passes all checks. • Check If the input string begins with '-' or '+', remove this sign from the beginning of input sting. Recheck if the input string is now empty and if so return the appropriate invalid number message. • Check if the input string has any '+' or '- signs remaining. If so return the appropriate invalid number message. Check if the input string has a sequence of two spaces. If so return the appropriate invalid number message. • Remove all spaces from the input string. Now check for appropriate use of commas and decimal point. To do this first, break the input string into two strings: one containing all characters before a decimal point and another for characters after. If there is no decimal point consider all characters before the decimal point and no characters after. Then: • Check if the after string contains a decimal point. If so, return the appropriate invalid number message. • Check if the after string contains a comma. If so, return the appropriate invalid number message. Check to see if the before string matches a pattern that begins with one, two, or three digits followed by a comma and three digits where the pattern of a comma followed by three digits can be repeated one or more times. If so, remove all commas from the input string. . • Check if the input string has a comma. If so, return the appropriate invalid number message. • Check if the remaining input string contains a character other than digits or one decimal. If a non-digit or decimal point is found, return the appropriate invalid number message. The above can be solved using the String methods: ● contains trim .indexOf ● ● · substring replaceAll length • toCharArray • matches Be careful to code the statements that modify the input string. Keep in mind that Strings are immutable. Methods like trim and replace all do not modify a String. Instead, they return a String. These methods when used should be in the context of an assignment statement where the variable referencing the input string is assign the returned String. File is marked as read only 1 import java.util.Scanner; 2 3 public class Main { 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String line = scnr.nextLine(); String preppedLine StringUtils.prepNumber(line); if (preppedLine.startsWith("Invalid")) { System.out.println(preppedLine); } else { } Current file: Main.java } System.out.printf("%,. 2f", Double.parseDouble(preppedLine)); 1234567 00 1 public class StringUtils { // Add your code here 7} 8 Current file: StringUtils.java Load default template..
Expert Answer:
Answer rating: 100% (QA)
public class StringUtils public static String prepDoubleString str String stripped strreplaceAlls replaceAll int len strippedlength if len 0 return In... View the full answer
Related Book For
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill
Posted Date:
Students also viewed these programming questions
-
Consider user accounts on a system with a Web server configured to provide access to user Web areas. In general, this scheme uses a standard directory name, such as public_html, in a users home...
-
One end of a steel rectangular girder is embedded into a wall (Fig. 1.74). Due to gravity it sags slightly. Find the radius of curvature of the neutral layer (see the dotted line in the figure) in...
-
A string can have a free end if that end is attached to a ring that can slide without friction on a vertical pole (Fig. 11-57). Determine the wavelengths of the resonant vibrations of such a string...
-
Why are lipids and proteins free to move laterally in membranes? O a. Lipids and proteins repulse each other in the membrane O b. The interior of the membrane is filled with liquid water Oc. There...
-
Use Solver to create a Sensitivity Report for question 31 at the end of Chapter 3 and answer the following questions. a. Is the solution degenerate? b. Is the solution unique? c. How much should the...
-
Marlon wants to use the right interest rate to calculate his needs in retirement. If he thinks his investments will continue to get an 8% nominal return and that inflation will slow to 2%, What is...
-
Describe the various roles of advanced practice nurses.
-
What is the present worth of a series of equal quarterly payments of $3000 that extends over a period of 8 years if the interest rate is 10% compounded monthly?
-
What are some of the advantages and disadvantages of the four most common methods for gathering information for a systems survey? Which one(s) of them makes the most sense for your company, and...
-
Here is a simplified diagram of a RF front end (power and control signals are not shown). 1. What kind of a system is it? What are the RF measurements you would use to characterize it and compare it...
-
Assume you want to purchase a $300,000 home. You wish to put a 20% down payment to avoid paying PMI (private mortgage insurance). You would like a 15-year fixed mortgage. The broker quotes you an...
-
In the machine with homogeneous limbs, the L-length 2nd limb is under the effect of Mah moment, and limb 4 is under the effect of horizontal F force. q is the main coordinate, and r and x are the...
-
The following table presents some statistics about the returns of three assets, A, B and C, respectively, under three possible scenarios (Boom, Normal and Recession). The expected probabilities of...
-
This exercise addresses some issues related to calculating real GDP. Consider a model economy with only two goods. The following table shows the prices and quantities of goods produced: Year 1 2 3 4...
-
You will create a cost function for this exercise using your birthday. Make note of your birthday using the number of the month (1-12) and the number for the day of the month (1-31) below. Month (m):...
-
Top Hat, Inc. has closed out their 2022 tax year. The client is a manufacturer and has inventory. They are taxed as a C Corporation and use the accrual method of accounting for their financial...
-
how many economic branches? explain it.
-
a. Why does the Wi-Fi Alliance release compatibility testing profiles in waves instead of combining the entire standards features initially? 27a1.) An 802.11ac Wi-Fi compatibility testing profile...
-
Jim is fired from his job as a waiter and decides to take an extended trip to Europe. After touring Europe for 3 months, Jim returns to look for a new job as a waiter. Are his job-hunting expenses...
-
In 2012, Margaret and John Murphy are married taxpayers who file a joint tax return with AGl of $25,000. During the year they incurred the following expenses: Hospitalization insurance...
-
In June of 2012, Maureen's house is vandalized during a long-term power failure after a hurricane hit the city. The president of the United States declares Maureen's city a disaster area as a result...
-
What circumstances might lead you to write-off a debt as bad and not close the debtor's account?
-
A business had always made an allowance for doubtful debts at the rate of 3 per cent of accounts receivable. On 1 January 2015 the amount for this, brought forward from the previous year, was 400....
-
A business started trading on 1 January 2014. During the two years ended 31 December 2014 and 2015 the following debts were written off to the Bad Debts Account on the dates stated: On 31 December...
Study smarter with the SolutionInn App