Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I have a combo box that i plan to put quite a few items in, each of these items need to equal a number because depending on what item is picked, the number it stands for will be added to another number.

 

Heres a little bit of the code im using now and i was wondering if there is a better way to do it:

       Dim WeaponPower As String
       If comboWeapon.Text = "Fists Only" Then
           WeaponPower = 0
       End If
       If comboWeapon.Text = "Bronze Long Sword" Then
           WeaponPower = 7
       End If
       If comboWeapon.Text = "Adam Long Sword" Then
           WeaponPower = 32
       End If

 

It just seems like alot of code if i keep putting the If..... Then part, maybe theres some easier way.

 

Thanks.

  • Leaders
Posted

First of all, a Select Case would be much better suited for this. It will run faster (though I doubt this will be an issue) and require less code.

 

   Dim WeaponPower As Integer
   Select Case comboWeapon.Text 
       Case "Fists Only" 
           WeaponPower = 0
       Case "Bronze Long Sword"
           WeaponPower = 7
       Case "Adam Long Sword" Then
           WeaponPower = 32
   End Select

 

If you have a substantial amount of weapons consider doing it like this:

 

   Dim Weapons As String() = {"Fists Only","Bronze Long Sword","Adam Long Sword"}
   Dim Power As Integer() = {0, 7, 32}

   Function PowerOfWeapon(Weapon As String)
       Dim i As Integer
       Do While i < Weapons.Length 'Until we reach the end of the weapon list
           If Weapons(I) = Weapon 'If we have a match return the weapons power
               Return Power(i)
           EndIf
           i += 1
       Loop
       'At this point there is no match. You could
       'just return zero, or throw an exception.
   End Function

 

The second method creates two lists in the form of arrays: a list of weapons and a list of their respective strength. The function searches the list of weapons until a match is found and returns the respective power.

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...