Searching arrays for values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • negus
    New Member
    • Jan 2010
    • 18

    Searching arrays for values

    alrighty i am working on a VB project for Chem and im making it for converting grams to moles, moles to molecules or any thing like that. and i have about 110 elements set up and working fine the way that im doing it but i have a feeling this is a horrible way and to abundant.

    i have a textbox set up to if i type in the element He and hit enter it will find ChemElement(1)= "He" and it calls
    "Sub DisplayElement( ByVal number As Decimal, ByRef label2 As Label)"
    Which then displays the Chemical mass into a Label.

    so basically here is my code

    Code:
    If TextBox1.Text = ChemElement(0) Then
                Call DisplayElement(ChemMass(0), Me.Label2)
            ElseIf TextBox1.Text = ChemElement(1) Then
                Call DisplayElement(ChemMass(1), Me.Label2)
    Code:
     Sub DisplayElement(ByVal number As Decimal, ByRef label2 As Label)
    Labe2.text=number
    now what my question is after we got all that settled is, is there a way to set this up so what ever is entered in my TextBox1 say element "B", that i could code it up to find ChemElement(4)= "B".
    i ask for knowledge on arrays, and i have been doing some research on arrays but cannot seem to find any help. because this coding works that i have it is just very long and harsh.

    thank you anyone for help.
    -negus
  • semomaniz
    Recognized Expert New Member
    • Oct 2007
    • 210

    #2
    use a foreach loop. Check the value entered with the values inside the array using foreach or for loop and do the processing

    Comment

    • negus
      New Member
      • Jan 2010
      • 18

      #3
      im not really familiar with those but im in programming 2 course through my highschool looked it up in the text book and found some information but still a lil foggy about it,

      how about using my string/array.

      dim ChemElement(109 ) as string ((or array not sure which one to use)).

      but using the IndexOf function. would it be more efficient to do it that way or not? and if so could you help me with a example code based off of my codes uptop?

      Comment

      • !NoItAll
        Contributor
        • May 2006
        • 297

        #4
        Unless you are dealing with a particularly large array - a quick enough method is to use a for loop. This gives you the ability to do a case insensitive search and will likely return your answer before the mouse button is all the way up.

        This simple function will return the index of the first matching item in the array, or -1 if nothing was found. It also assumes your array is an array of strings...

        Code:
        Friend Function LookFor(ByVal sItemToFind as String, ByVal Array() as String) as Integer
        
        Dim iLoc as Integer = -1
           For each Item as String in Array
               
              iLoc +=1
               If Item.tolower = sItemToFind.tolower then
                   Return iLoc
                End if
        
           Next Item
        
           Return -1
        End Function
        I assume you need the index, or you just want to know if something is actually in the array.

        Comment

        • negus
          New Member
          • Jan 2010
          • 18

          #5
          well yea it is rather large, i have two strings with 110 elements in each.

          one is ChemElement(109 ) as string with proceding ChemElement 110 times setting each to a different Chemical element so,

          ChemElement(0) = "H"
          "" ""
          ChemElement(16) = "Cl"

          and my other string that contains 110 elements is ChemMass(109) that is set to = the chemical mass of each element so for example.

          ChemMass(0) = 1.01
          ChemMass(16) = 35.453

          maybe all of you have answered this and im being completely dumb right now but my official goal is to type into my Textbox1 say "Be" and when i hit the button it realizes that the "Be" entered in the textbox is equal to ChemElement(3) and ChemMass(3).

          Comment

          • !NoItAll
            Contributor
            • May 2006
            • 297

            #6
            Ok - by huge I meant on the order of maybe 10-thousand. An array of 110 items is, by most any standard, tiny. I now see what you are trying to do and there is actually a better way to do this. Create a structure.
            Try this:
            Code:
            Friend Structure Chems
                Element as String
                Mass as String
            End Structure
            Friend Const MAXCHEMS as integer = 109
            Friend MyChems(MAXCHEMS) as Chems    'this is the array you will use

            So now you have an array of the Chems structure called MyChems you can use to carry both values. You then fill the structure in (perhaps in your On-Load event if you are using a windows forms project):
            Code:
            MyChems(0).Element = "H"
            MyChems(0).Mass = "1.01"
             .
             .    put the rest of the periodic table in here
             .
            MyChems(109).Element = "Cl"
            MyChems(109).Mass = "35.453"

            Now you can build a simple function to find what you want
            Code:
            Friend Function FindMass(ByVal sLookFor as String, ChemArray() as Chems) as String
            
            For I as Integer = 0 to (ChemArray.Length -1)
                
                If ChemArray(I).Element.ToLower = sLookFor.trim.tolower then
                        Return ChemArray(I).Mass
                End if
            
            Next I
            
            Return ""
            End Function

            You have the user type in the name then pass the name and MyChems array into the function and it will return the weight, or an empty string if the name was not found.
            With a little bit more code you could get a tiny bit fancier by making the function return the name if the user entered the weight too:
            Code:
            Friend Function FindMyChem(ByVal sLookFor as String, ChemArray() as Chems) as Chems
            
            Dim Empty as Chems
            Empty.Element = ""
            Empty.Mass = ""
            
            For I as Integer = 0 to (ChemArray.Length -1)
                
                If ChemArray(I).Element.ToLower = sLookFor.trim.tolower then
                        Return ChemArray(I)
                Elseif ChemArray(I).Mass.ToLower = sLookFor.Trim.ToLower then
                        Return ChemArray(I)
                End if
            
            Next I
            
            Return Empty
            
            End Function

            In the second case you are returning a one-dimensional version of the Chemarray so you call it like this:
            Code:
            Dim AnswerChem as Chems = FindMyChem(sEntry, MyChems)

            So you will get AnswerChem back with two elements that have the name and the weight

            AnswerChem.Elem ent will have the Element Name
            AnswerChem.Mass will have the Mass

            They will both be empty strings if no result was found (thats why I built the Empty Chems array at the beginning - so I would have an empty array to return if no match was found).

            Zipping through an array of 110 elements will take a millisecond or so and will likely be completed before the user moves his/her eyes to the result window. Notice I am trimming the input from the user in case they add a space at the beginning or end, and I do a tolower for each one. I did this so you can use capitalization in your chemical names for when you display them (for readability), but I lower case them (and the user input) for comparison purposes. The comparison function is case sensitive and lowercasing them both for the comparison makes it, in effect, non-case sensitive - and much friendlier for the user.

            This (Single structure -vs- two individual arrays) is considered a better approach because you have created a single structure to carry both portions of your information. While creating two arrays is fine - it's considered bad form because they are not really connected in any way. Down the road, when your programs get more complex you will want to make sure you aren't making changes to one array separately from the other and getting your data out-of-sync.

            Like anything in coding there are many ways to accomplish the same goal.

            Comment

            • negus
              New Member
              • Jan 2010
              • 18

              #7
              i really appreciate your help here! i knew there was a more efficient way of doing this and my approach was not well organized. this helped 110%.

              and thanks for actually putting some code in there for me to visualize what is going on, i will work on this in my next class period and hopefully get good results=]

              Comment

              • negus
                New Member
                • Jan 2010
                • 18

                #8
                one question, what do i set my textbox.text = to under my button1_click sub
                and how do it get value into a label. i know how to do it but with this code not quite sure what to use in the code

                Comment

                • !NoItAll
                  Contributor
                  • May 2006
                  • 297

                  #9
                  Assuming your textbox is where the user enters the element name then you don't set it to anything - you only read it for the input and send it to the function. You can set the label (which I assume will display the answer) in the same line.

                  Code:
                  AnswerLabel.text = FindMyChem(Textbox.text, MyChems)
                  This part is very very basic and I might now suggest you run a tutorial on vb.net to get started.

                  Comment

                  • negus
                    New Member
                    • Jan 2010
                    • 18

                    #10
                    Yeah I did that code before I posted on here again, I overpassed one of my functions. Thanks for the help!

                    Comment

                    • negus
                      New Member
                      • Jan 2010
                      • 18

                      #11
                      I'm really sorry to bug again but how would i go about typing chemical compounds in my textbox and returning it with the mass.

                      Compound as in H2O (H+H+O)=18
                      rather than having multiple textbox's for each element in the compound

                      Comment

                      • !NoItAll
                        Contributor
                        • May 2006
                        • 297

                        #12
                        Code:
                        Dim ElementArray() as String - textbox.text.split("+")
                        Dim iAggregate as Integer = 0
                        
                        For each sElement as String in ElementArray
                        
                             iAggregate += Cint(findmychem(sElement, MyChems))
                        
                        Next
                        
                        AnswerLabel.text = iAggregate.ToString
                        You'll need to modify findmychem to return 0 instead of blank if the element isn't found.

                        Comment

                        • negus
                          New Member
                          • Jan 2010
                          • 18

                          #13
                          i get a error for some reason in the

                          iAggregate += Cint(findmychem (selement, mychems))

                          Error 1 Value of type 'WindowsApplica tion1.Form2.Che ms' cannot be converted to 'Integer'.

                          Comment

                          • !NoItAll
                            Contributor
                            • May 2006
                            • 297

                            #14
                            Oh yes - I forgot. Mass is not an integer since it has a floating point. Use this

                            Dim iAggregate as Double

                            Then in the loop use:

                            iAggregate += CDbl(findmychem (selement, mychems))

                            Comment

                            • negus
                              New Member
                              • Jan 2010
                              • 18

                              #15
                              yea i was trying to figure the problem out myself and i already switched it to decimal, and double.

                              the same error comes up for the double it says:
                              Error 1 Value of type 'WindowsApplica tion1.Form2.Che ms' cannot be converted to 'Double'.

                              hmm

                              Comment

                              Working...