Reading a value from a string.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ian Smith

    Reading a value from a string.

    If I had a string value of

    "1 - This is the number one"

    Is there a method for reading just the integer value 1? I was looking and I found the method for adding each byte into an array. I supposed that I could read the first array value but that seemed to be quite a bit more work than was required. What method would you use?
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    You can split the string on some delimiter(Say '-' in this case). And then extract first part from resulting array.

    Regards
    Dheeraj Joshi

    Comment

    • pbrockway2
      Recognized Expert New Member
      • Nov 2007
      • 151

      #3
      You don't what the possible values of this integer are.

      If the integer value is just one digit long you could use the String substring(int,i nt) method to make a String with just the first character. The the static Integer method parseInt() can be used to find the int value corresponding to this string. (There are also String and Character methods that will work with the first character directly - not as a one digit string)

      Comment

      • Ian Smith

        #4
        I was thinking something very similar to that, then I found...

        Code:
        char name = stringName.charAt(0);
        This is exactly what I was looking for. I found this right after I asked the question. I swear sometimes I do not find an answer myself, until I ask a question. After that I just converted the char to an INT and all was good. Perhaps not the most "elegant" method but it works great for what I am using it for.

        Comment

        • Ian Smith

          #5
          In case you are wondering. I have created an array of buttons. I wanted the label on the button to be more descriptive. So...

          Code:
          center[i] = new JButton("Text " + (i+1) " more text " + arrayValue[i] + " more text " + array2value[i]);
          Each button is created with accompanying text inside of the loop. So now the action listener uses getText and charAt(5) gets the number. I wasn't certain how I wanted to accomplish getting the value from the button. I needed this value to accomplish further calculations based on the array values. This is working perfectly now, because the number (i+1) is static and matches the array after I subtract 1 from the converted char.

          Comment

          • pbrockway2
            Recognized Expert New Member
            • Nov 2007
            • 151

            #6
            I found this right after I asked the question. I swear sometimes I do not find an answer myself, until I ask a question.
            Same with me! I'm glad you've got it worked out.

            Comment

            Working...