• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using HashMap object to convert text to integer value

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

My program objective is to convert text into its corresponding int form, perform arithmetic operation [in this case add & then multiply] and display the result.
To implement this, the program uses a map object with String, Integer as its key, Value pair.

Please find the program

and its output
Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
ten
Enter integer value 2 (as text) between 0 to 99:
sixteen
ten * sixteen = 160..........correct

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
forty
Enter integer value 2 (as text) between 0 to 99:
five
forty * five = 200..........correct

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
sixty six
Enter integer value 2 (as text) between 0 to 99:
two
sixty six * two = 132..........correct

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
two
Enter integer value 2 (as text) between 0 to 99:
sixty six
two * sixty six = 132..........correct

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
sixty six
Enter integer value 2 (as text) between 0 to 99:
sixty six
sixty six * sixty six = 4356..........correct

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
sixty-six
Enter integer value 2 (as text) between 0 to 99:
two
sixty-six * two = 264..........incorrect

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
two
Enter integer value 2 (as text) between 0 to 99:
sixty-six
two * sixty-six = 264..........incorrect

Enter 'Y' to continue OR 'N' to exit program:
y
Enter integer value 1 (as text) between 0 to 99:
sixty-six
Enter integer value 2 (as text) between 0 to 99:
sixty-six
sixty-six * sixty-six = 17424..........incorrect

Enter 'Y' to continue OR 'N' to exit program:
n

For your better understanding, the program:
  • takes input from the user two int values in text form
  • creates a String[] str, of size 100, having String elements "zero","one", "two",............,"ninety-nine"
  • creates a Map object map whose run-time implementation is HashMap which maps String object to Integer value
  • loops thru the String[] str and assigns the int value corresponding to each array element [being the key-value pair]
  • creates another String[] splitNum, of size 2, to split user input [read as String] having hyphenated words
  • checks [i know too many if statements ]whether user input contains single text OR hyphenated words OR words with
    space inbetween [assuming the user forgets to hyphenate two word text]
  • Post splitting of hyphenated words, within the for loop, assigns values to each string before & after the hyphen, sums
    them and then multiplies result [of user input 1] with the result of user input 2
  • Finally, displays the result on the screen


  • Issue faced:
    The issue arises when checking for either of the user input(s) for hyphen. Somehow, the map object doubles the values mapped to the corresponding text - is
    the object duplicating the keys? If so, this contravenes its javadoc - and displays the
    same in the output [therefore reason for my writing on this forum as I'm unable to resolve on my own], whereas the if condition checking for space
    returns the correct result!

    My queries:
    a) Is the problem in the lines of code 77 to 87 and 107 to 117 for either of the inputs OR elsewhere in the code that returns incorrect result for hyphenated words??
    b) Could anyone suggest alternatives to the many if statements in the code.

    Much appreciated if any of the forum experts could help in identifying the error(s) and resolving the same.

    Thanks,
    Sudhir
     
    Bartender
    Posts: 4568
    9
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I haven't trawled through the rest of the logic, but this bit looks strange to me:
    That means "if it doesn't contain a hyphen or it doesn't contain a space". Is that really what you want? That will be true for every input you've shown, and is only false for inputs that contain both.
     
    Bartender
    Posts: 1166
    17
    Netbeans IDE Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Why not just remove all spaces and hyphens from the input supplied by the user and from the keys when generating the map. Keep the hyphens in the arrays though so you can display the result with hyphens. This way you just have to replace all spaces or hyphens with the empty string; a simple one line regular expression.
     
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    You have a contradiction in the specification you wrote out. In one place you say “sixty six” and in another “ninety-nine”. Please check that.
    You can use the replace methods of the String class, and maybe toLowerCase, too, to convert sIxTy     sIX to sixty‑six.

    Why are you trying to put things in the map after using String#split? You have got all things out of order. Start by reducing the main method to its ideal length: 1 statement. Create a class or some classes which will encapsulate your logic. One will have the Map as a field. Create methods to input the two numbers and the operator, and to do the calculation. Don't try to do the whole thing all at once. Do it in bits, and write methods which test each part before the app is complete.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thank you Matthew, Richard and Campbell for your prompt responses.

    As you have quite a few suggestions for modifying and improving the program code, will need some time for the same. Will revert with modified code once completed.

    Regards,
    Sudhir
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    As per Richard's suggestion

    Richard Tookey wrote:Why not just remove all spaces and hyphens from the input supplied by the user and from the keys
    when generating the map.......... This way you just have to replace all spaces or hyphens with the empty string; a simple
    one line regular expression.


    this pseudocode (of sorts, if one may call that)

    a) for the removal of hyphens / spaces at the time of generating the map

    b) for the calculation part

    provided would display the result without bothering about hyphens / spaces in the text (user input to omit hyphens /
    spaces for ex: twentyfive, seventytwo etc..etc..etc). The code derived from this (hope the pseudocode is not complex or
    incomprehensible) replaces the lines of code 58 to 130 in my original posting. It certainly shortens the code from 72 lines to approx. 20 lines.

    and output from program

    To further refine the code, will work on Campbell's suggestions

    Campbell Ritchie wrote: Start by reducing the main method to its ideal length: 1 statement. Create a class or some classes which will encapsulate your logic. One will have the Map as a field. Create methods to input the two numbers and the operator, and to do the calculation...........


    (adhering to java fundamental, OOP) and revert.
     
    Richard Tookey
    Bartender
    Posts: 1166
    17
    Netbeans IDE Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Since you will only ever lookup an integer using the alpha representation of the integer you only need one Map<String,Integer>. That use as key the normalised alpha representation with hyphens and spaces removed (a simple regex will do this) and converted to lower case (or upper if you prefer). The Map can be generated from the arrays of alpha representation without the need to check whether or not a key is already being used since you will make sure the arrays do not contain duplicate values.

    When an alpha representation is supplied your just normalise it an look it up in the Map<String,Integer> to get the numeric value.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:
    Why are you trying................ Don't try to do the whole thing all at once. Do it in bits, and write
    methods which test each part before the app is complete.



    From Campbell's suggestions,

    the Pseudocode [for OOP based application]



    and its program output

    Please Note:
  • All classes to be within the same package of the project.
  • Fields / variables within the classes to be private & accessible only thru their respective methods.


  • I hope the pseudocode is not incomprehensible and complicated. Although a trifle lengthy [in my attempt at ease &
    simplicity], I think it can be translated to actual code without too much effort.

    I've modified the String[] to contain values without hyphens / spaces corresponding to user inputs. An update to the pseudocode would be
    to incorporate hyphens / spaces to be matched to the user inputs

    Richard Tookey wrote:Since you will only ever lookup an integer using the alpha representation of the integer you only need one
    Map<String,Integer>. That use as key the normalised alpha representation with hyphens and spaces removed (a simple regex will do this)............


    by way of a simple regex expression as suggested by Richard. Will post the same on completion.
     
    Richard Tookey
    Bartender
    Posts: 1166
    17
    Netbeans IDE Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:

    Richard Tookey wrote:Since you will only ever lookup an integer using the alpha representation of the integer you only need one
    Map<String,Integer>. That use as key the normalised alpha representation with hyphens and spaces removed (a simple regex will do this)............


    by way of a simple regex expression as suggested by Richard. Will post the same on completion.



    You don't need to modify the String[] containing the alpha representations! You just need to normalise each one when using it as a key in the Map! You normalise the String[] entry when building the Map and you normalise the user's input when looking up the value in the Map.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Okay. I think I've got it. Modifying the Pseudocode in my previous post

    Richard Tookey wrote:You don't need to modify the String[] containing the alpha representations!


    the String[] str containing the original values (with hyphens / space).


    Richard Tookey wrote:You just need to normalise each one when using it as a key in the Map! You normalise the String[]
    entry when building the Map


    At the time of building the map object sendMap, by looping thru the String[] str & adding the key-value pairs to this object, replace each
    array element - containing hyphen / space - with empty string. Converts all the text, within the map, into a common form with the
    corresponding values.

    Richard Tookey wrote:
    and you normalise the user's input when looking up the value in the Map.


    In the GetValues class, when setting the respective field within the setter method, replace the hyphen / space with empty
    string. Converts the user input to a common form.

    In the MapTxtToInt class,
  • just set (& return) the (normalized) map object sendMap passed from TestNaturalLanguageMultiply
  • within the getter methods,

    Sudhir Srinivasan wrote:
    - attributes inherited from GetValues
    - getter method 1:
    .. Iteratively, for each String output [output being variable name] in the keySet of tempMap
    .. check for String equality of user input 1[access & get superclass method] with output. If true..........


    check for String equality of normalized user input with that of the keySet of the normalized map object. If true,
    get the values corresponding to the same & do the calculation.

  • This obviates the need
  • for creating a separate map object and also
  • for lines of pseudocode [12-17] of MapTxtToInt in my previous post

  • [sidebar]
    If I've still not got it right (*sigh*), could you please provide the sample code (Richard, a big thank you for your time
    and patience)
    that simplifies my program as suggested.
    [/sidebar]

    Program output:
     
    Richard Tookey
    Bartender
    Posts: 1166
    17
    Netbeans IDE Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:Okay. I think I've got it.



    Well done. Though I can't see your latest code so I can't be certain it does seem you have got it right now..
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Richard Tookey wrote:Though I can't see your latest code so I can't be certain....


    The updated code snippets based on my understanding of your suggestions.

    Sudhir Srinivasan wrote:At the time of building the map object sendMap, by looping thru
    the String[] str & adding the key-value pairs to this object,...

    Richard Tookey wrote:You
    just need to normalise each one when using it as a key in the Map! You normalise the String[]
    entry when building the Map...



    Sudhir Srinivasan wrote:In the GetValues class, when setting the respective field
    within the setter method,....

    Richard Tookey wrote:and you normalise the user's input
    when looking up the value in the Map.



    Sudhir Srinivasan wrote:In the MapTxtToInt class,

  • just set (& return) the (normalized) map object sendMap passed from
    TestNaturalLanguageMultiply....

  • ......check for String equality of normalized user input with that of the keySet
    of the normalized map object.

    Richard Tookey wrote:and you normalise the user's input when looking up
    the value in the Map.


     
    Bartender
    Posts: 10780
    71
    Hibernate Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:The updated code snippets based on my understanding of your suggestions.


    Sudhir,

    It's too late for this thread, I suspect, but for future reference: Please DontWriteLongLines.
    It makes your thread very hard to read, and it's actually bad coding practice. Please remember in future:
    80 characters max.
    (the SSCCE page actually recommends 62)
    And that includes string literals AND comments AND long method calls.

    Thanks.

    Winston
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:

    Sudhir Srinivasan wrote:The updated code snippets based on my understanding of your suggestions.


    Sudhir,

    It's too late for this thread, I suspect, but for future reference: Please DontWriteLongLines.



    Hi Winston,
    I've edited my last post and shortened the lines as suggested.

    I shall certainly keep your suggestions in mind when posting in the future. Any inconvenience caused to the moderators / responder(s)
    is regretted.

    Regards,
    Sudhir


     
    Winston Gutkowski
    Bartender
    Posts: 10780
    71
    Hibernate Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:Hi Winston,
    I've edited my last post and shortened the lines as suggested.
    I shall certainly keep your suggestions in mind when posting in the future. Any inconvenience caused to the moderators / responder(s)
    is regretted.


    No probs. It's as much for you as it is for us; and I'm afraid that it's not just your last post.

    Do you find looking at that first post of yours restful? I don't.

    You might want to have a look at this page; except change the 120
    in section 1.4 to 80.

    Back in the dark ages, coding sheets were 80 characters long; and I reckon it's still a good rule of thumb to stick to.

    HIH

    Winston
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    reply
      Bookmark Topic Watch Topic
    • New Topic