Lanc1988 Posted February 12, 2005 Posted February 12, 2005 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. Quote
michael_hk Posted February 12, 2005 Posted February 12, 2005 Maybe create a Weapon class class Weapon { private string name = "Fists Only"; private int power = 10; // contructor, methods etc go here } Quote There is no spoon. <<The Matrix>>
Leaders snarfblam Posted February 13, 2005 Leaders Posted February 13, 2005 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. Quote [sIGPIC]e[/sIGPIC]
Lanc1988 Posted February 13, 2005 Author Posted February 13, 2005 ok thanks, the select case code works just how i need it to, i should have thought of it since im using it for something else already :P Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.