I am working on a payroll program. The first base class is bonus the class should contain 2 public properties salesid and sales.
Include a default constructor and a parameeterized constructor in the class.Also include a a getbonus method(function) that calculates a salespersons bonus using the formula sales*0.05
create a derived class named Premiumbonus the derived clas getbonus mothod calculate the bonus as follows sales0.05 +(sales-2500)).01 also include a default and parameterized constructorin this derived class.
if the sales is over 2500 use this
I feel like my math is off can someone please double check it? I need some suggestions and also i tried to debug and getbonus seems like it stays on 0 no matter what number i put but I get results in the calculated box.
below is the code
Option Explicit On
Option Strict On
Option Infer Off
' base class
Public Class Bonus
Public Property SalesId As String
Public Property Sales As Double
Public Sub New()
_Sales = 0
_SalesId = String.Empty
End Sub
Public Sub New(ByVal dblB As Double,
ByVal strId As String)
_Sales = dblB
_SalesId = strId
End Sub
Public Overridable Function GetBonus() As Double
' returns sales
Return _Sales * 0.05
End Function
End Class
' derived class
Public Class PremiumBonus
Inherits Bonus
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal dblB As Double,
ByVal strId As String)
MyBase.New(dblB, strId)
End Sub
Public Overrides Function GetBonus() As Double
Return MyBase.GetBonus + (Sales - 2500) * 0.01
End Function
End Class
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
' calculates and displays a bonus
Dim myBonus As New Bonus
Dim myPremiumBonus As New PremiumBonus
Dim Sales As Double
' if the sales are over $2500, instantiate a PremiumBonus object
' and then calculate the bonus
' otherwise, instantiate a Bonus object and then calculate the bonus
If Sales > 2500 Then
Double.TryParse(txtSales.Text, myBonus.Sales)
Sales = myBonus.GetBonus
Else
Double.TryParse(txtSales.Text, myPremiumBonus.Sales)
Sales = myPremiumBonus.GetBonus
End If
Based on your title:
Payroll program not displaying correct amount results
and part of your description:
getbonus seems like it stays on 0 no matter what number i put but I get results in the calculated box
I am pretty certain your question is "My output is zero regardless of input. What's wrong?"
I see in your code:
Dim Sales As Double
If Sales > 2500 Then
Double.TryParse(txtSales.Text, myBonus.Sales)
Sales = myBonus.GetBonus
You should probably look at populating Sales with a value prior to evaluating it, and it's probably a good idea not to use the same variable name in so many places, as it makes your code more difficult to read. You might try something like this:
Dim myNewBonus As Double
Dim Sales As Double
Double.TryParse(txtSales.Text, Sales)
If Sales > 2500 Then
myBonus.Sales = Sales
myNewBonus = myBonus.GetBonus()
Any if that still fails try using the debugger, or at least some strategically placed MessageBox.Show(someValueIShouldCheck.ToString)'s
thanks anyway I fixed it I had the bonuses in the wrong spots
Public Class Bonus
Public Property SalesId As String
Public Property Sales As Double
Public Sub New()
_Sales = 0
_SalesId = String.Empty
End Sub
Public Sub New(ByVal dblB As Double,
ByVal strId As String)
_Sales = dblB
_SalesId = strId
End Sub
Public Overridable Function GetBonus() As Double
' returns sales
Return _Sales * 0.05
End Function
End Class
' derived class
Public Class PremiumBonus
Inherits Bonus
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal dblB As Double,
ByVal strId As String)
MyBase.New(dblB, strId)
End Sub
Public Overrides Function GetBonus() As Double
Return MyBase.GetBonus + (Sales - 2500) * 0.01
End Function
End Class
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
' calculates and displays a bonus
Dim myBonus As New Bonus
Dim myPremiumBonus As New PremiumBonus
Dim Sales As Double
' if the sales are over $2500, instantiate a PremiumBonus object
' and then calculate the bonus
' otherwise, instantiate a Bonus object and then calculate the bonus
If Val(txtSales.Text) > 2500 Then
Double.TryParse(txtSales.Text, myPremiumBonus.Sales)
Sales = myPremiumBonus.GetBonus
Else
Double.TryParse(txtSales.Text, myBonus.Sales)
Sales = myBonus.GetBonus()
End If
Related
Imports Kerry_Sales_Project
' base class
Public Class Bonus
Public Property SalesId As String
Public Property Sales As Double
' default constructor
Public Sub New()
_SalesId = String.Empty
_Sales = 0
End Sub
' parameterized constructor
Public Sub New(ByVal strId As String, ByVal dblSold As Double)
SalesId = strId
Sales = dblSold
End Sub
' GetBonus method
Public Overridable Function GetBonus() As Double
Return _Sales * 0.05
End Function
Public Shared Widening Operator CType(v As PremiumBonus) As Bonus
Throw New NotImplementedException()
End Operator
End Class
' derived class
Public Class PremiumBonus
Public Property Sales As Double
Public Property strId As String
' default constructor
Public Sub New(strId As String)
MyBase.New()
End Sub
' parameterized constructor
Public Sub New(ByVal strId As String, ByVal dblSold As Double)
MyBase.New(strId, dblSold)
End Sub
' class method
Public Overrides Function GetBonus() As Double
Return MyBase.GetBonus() + (Sales - 2500) * 0.01
End Function
End Class
In effect, you forgot to place Inherits Bonus in the Premium Bonus class. It would be something like
Public Class PremiumBonus: Inherits Bonus
And the other thing is the CType operator overload.
Public Shared Widening Operator CType(v As PremiumBonus) As Bonus
Throw New NotImplementedException()
End Operator
This operator overload is not necessary because the PremiumBonus class is a child of Bunus and they are contained.
I'm doing an IT course for college and one of the assignments requires you to create a BMI calculator in Visual Basic with the use of object orientated techniques. I'm not a very good programmer and thus I'm stuck on a problem I keep receiving. The code I'm using was given to me by someone who claimed it works, however when I run the program any results given are NaN.
Anyone have an idea as to what is wrong with the code in order to give me this result?
Here is the code I'm using:
Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles
Button_Calculate.Click
Dim height As Double = Double.Parse(TextBox_Height.Text)
Dim weight As Double = Double.Parse(TextBox_Weight.Text)
bmi.SetWeight(weight)
bmi.SetHeight(height)
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Private bmi As New BMI
End Class
In a separate class:
Public Class BMI
Public Function GetBMI()
Return (weight / (height ^ 2))
End Function
Public Function GetWeight()
Return weight
End Function
Public Function GetHeight()
Return height
End Function
Public Function SetWeight(_weight As Double)
Return weight = _weight
End Function
Public Function SetHeight(_height As Double)
Return height = _height
End Function
Private weight As Double
Private height As Double
End Class
There are a few problems with your (meaning kushlord420) solution.
Visual Basic code in case insensitive so bmi is the same as BMI
You never use the Form level variable bmi so delete.
You tried to write a custom constructor but in vb.net it is Sub New
You are converting the values in the weight and height text boxes to Double but your properties are type Single. Actually this should
be Single.TryParse but that is for another day.
Functions in vb.net must have a data type for the return value. This is provided in the first line of the function. Since you are
using Format on the return value I made the value a String and
converted the return value.
Fixed the constructor parameters to avoid ambiguity.
Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
Dim bmi As New BMI(CSng(TextBox_Weight.Text), CSng(TextBox_Height.Text))
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Public Class BMI
Public Function GetBMI() As String
Return (Weight / (Height ^ 2)).ToString
End Function
Public Property Weight As Single
Public Property Height As Single
Public Sub New(wght As Single, hght As Single)
Weight = wght
Height = hght
End Sub
End Class
You really need something more like this:
Public Class BMI
Public Function GetBMI() As Double
Return (weight / (height ^ 2))
End Function
Public Property Weight As Double
Public Property Height As Double
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
Dim bmi As New BMI(CDbl(TextBox_Weight.Text), CDbl(TextBox_Height.Text))
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
End Class
Or better yet, this:
Public Class BMI
Public Property Weight As Double
Public Property Height As Double
Public ReadOnly Property BMI As Double
Get
Return (Weight / (Height ^ 2))
End Get
End Property
Public Sub New()
End Sub
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
With the help of a friend, figured out my problem.
If anyone is curious, here is the code that made it work:
Public Class Form1
Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles
Button_Calculate.Click
Dim bmi As New BMI With {.Weight = CDbl(TextBox_Weight.Text), .Height =
CDbl(TextBox_Height.Text)}
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Private bmi As New BMI
End Class
And:
Public Class BMI
Public Function GetBMI()
Return (weight / (height ^ 2))
End Function
Property Weight As Single
Property Height As Single
Public Sub BMI(weight As Single, height As Single)
Me.Weight = weight
Me.Height = height
End Sub
End Class
I have a class which inherit from Panel, and below are some member in this class
Public ItemName As String
Public Quantity As Integer
Public Price As Decimal
Public DiscountAmount As Decimal
How can I create a event when Quantity or DiscountAmount changed then run a function?
I try to write in this way but I get error:-
Private Sub info_Changed(sender As Object, e As EventArgs) Handles Quantity.Changed, DiscountAmount.Changed
myFunction()
End Sub
Error:
Handles clause requires a WithEvents variable defined in the
containing type or one of its base types.
You need to declare the events in user control and then consume those. See below code. I have created a user control UserControl1. This control raises events when Price or DiscountAmount is changed. The usercontrol is then used in Form1. You can use the same approach to change the Quantity.
Public Class Form1
Private WithEvents userCntrl As New UserControl1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ChangeValues()
End Sub
Private Sub ChangeValues()
userCntrl.Price = 100
userCntrl.DiscountAmount = 12
End Sub
Private Sub userCntrl_Price_Changed(newValue As Decimal) Handles userCntrl.Price_Changed, userCntrl.DiscountAmount_Changed
MessageBox.Show("New value = " & newValue.ToString)
End Sub
End Class
Public Class UserControl1
Public Event Price_Changed(ByVal newValue As Decimal)
Public Event DiscountAmount_Changed(ByVal newValue As Decimal)
Public ItemName As String
Public Quantity As Integer
Private Price_ As Decimal
Public Property Price() As Decimal
Get
Return Price_
End Get
Set(ByVal value As Decimal)
If value <> Price_ Then
RaiseEvent Price_Changed(value)
End If
Price_ = value
End Set
End Property
Private DiscountAmount_ As Decimal
Public Property DiscountAmount() As Decimal
Get
Return DiscountAmount_
End Get
Set(ByVal value As Decimal)
If value <> DiscountAmount_ Then
RaiseEvent DiscountAmount_Changed(value)
End If
DiscountAmount_ = value
End Set
End Property
End Class
I am trying to wrap an instance of a created class with another that share the same super class in Visual Basic 2013. I'm new to VB and been struggling with this.
This is for a Java to VB conversion..
Code example of what I have written:
' Abstract product creator Class
Public MustInherit Class PizzaMaker
' Abstract Method to create a pizza
Public MustOverride Function createPizza(ByRef size As Integer, ByRef crust As String) As Pizza
Public Function orderPizza(ByRef size, ByRef crust) As Pizza
Dim pizza As Pizza
pizza = createPizza(size, crust)
Return pizza
End Function
End Class
' Concrete factory Class
Public Class MargheritaMaker
Inherits PizzaMaker
' Override abstrat method in superclass
Public Overrides Function createPizza(ByRef size As Integer, ByRef crust As String) As Pizza
Dim pizza As New MargheritaPizza(size, crust)
Return pizza
End Function
End Class
' Abstract component product Class
Public MustInherit Class Pizza
' Consatant variables used for pizza size
Public Const SMALL As Integer = 1
Public Const MEDIUM As Int16 = 2
Public Const LARGE As Int16 = 3
Public Const EXTRA_LARGE As Int16 = 4
' Crust type of pizza
Private crustType As String
' Size of the pizza
Private size As Int16
' Description of the pizza
Public description As String = "Pizza"
' Abstract method to return the cost of the pizza
Public MustOverride Function getCost() As Double
' Returns size description
Public Function getSizeDescription() As String
Dim desc As String
' Determin pizza size and return String description
If (size = 1) Then
desc = "Small"
ElseIf (size = 2) Then
desc = "Medium"
ElseIf (size = 3) Then
desc = "Large"
Else
desc = "Extra Large"
End If
Return desc
End Function
Public Function getCrust() As String
Return crustType
End Function
' Sets the pizza crust type
Public Sub setCrust(ByRef crust)
crustType = crust
End Sub
' Returns the pizza size
Public Function getSize() As Integer
Return size
End Function
' Set the size of our Pizza
Public Sub setSize(ByVal i)
size = i
End Sub
' Returns the String description of the pizza
Public Function getDescription() As String
Return getSizeDescription() + " " + crustType + " " + description
End Function
End Class
' Concrete component product Class defining a Margherita Pizza
Public Class MargheritaPizza
Inherits Pizza
'Dim cost
' Constructor set's the Pizza size, crust type & description
Sub New(ByRef size As Integer, ByRef crust As String)
setSize(size)
setCrust(crust)
description = "Margherita Pizza"
End Sub
' Returns the Pizza base cost based on it's size
Public Overrides Function getCost() As Double
Dim cost As Double
If (getSize() = Pizza.SMALL) Then
'Console.Write("in if" & vbNewLine)
cost = 9.5
ElseIf (getSize() = Pizza.MEDIUM) Then
cost = 10.5
ElseIf (getSize() = Pizza.LARGE) Then
cost = 11.5
ElseIf (getSize() = Pizza.EXTRA_LARGE) Then
cost = 12.5
End If
'Console.Write("in if" * vbNewLine)
Return cost
End Function
End Class
' Abstract component product decorator Class
Public MustInherit Class PizzaDecorator
Inherits Pizza
' Abstract method that returns decorator description
Public MustOverride Overloads Function getDescription()
End Class
' Concrete component product decorator Class (used as Object wrapper)
Public Class Cheese
Inherits PizzaDecorator
Dim pizza ' As Pizza
' Check that the construtor paramaters are correct!!! Also check scope of variables!!!
Sub New(ByVal pizz)
pizza = pizz
'pizza.setSize(pizz.getSize())
'pizza.setCrust(pizz.getCrust())
End Sub
' Returns cost of product by delegating call to wrapped objects
Public Overrides Function getCost() As Double
Dim cost ' As Double = pizza.getCost()
If (pizza.getSize() = pizza.SMALL) Then
Console.Write(" In cheese pizza = SMALL" & vbNewLine)
cost += 0.1
ElseIf (pizza.getSize() = pizza.MEDIUM) Then
cost += 0.2
ElseIf (pizza.getSize() = pizza.LARGE) Then
cost += 0.3
ElseIf (pizza.getSize() = pizza.EXTRA_LARGE) Then
cost += 0.4
End If
Console.Write(" Pizza size = " + pizza.getSize().ToString & vbNewLine)
Console.Write(" in end if" & vbNewLine)
Return cost + pizza.getCost()
End Function
Public Overrides Function getDescription() As Object
Return pizza.getDescription() + ", Extra Cheese"
End Function
End Class
Then run a test with this:
Public Class TestForm
Public margheritaM ' As MargheritaMaker
Public pizza ' As Pizza
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Dim m As New MargheritaMaker()
'Dim pizza
'Dim margheritaM As New MargheritaMaker()
margheritaM = New MargheritaMaker()
pizza = margheritaM.createPizza(1, "Deep Pan")
MargheritaBox.AppendText(pizza.getDescription() & vbNewLine)
End Sub
Private Sub CheeseButton_Click(sender As Object, e As EventArgs) Handles CheeseButton.Click
'pizza As New Cheese(pizza)
pizza = New Cheese(pizza)
MargheritaBox.AppendText(pizza.getDescription() & vbNewLine)
End Sub
Private Sub CostButton_Click(sender As Object, e As EventArgs) Handles CostButton.Click
MargheritaBox.AppendText(pizza.getCost() & vbNewLine)
End Sub
Private Sub PepperoniButton_Click(sender As Object, e As EventArgs) Handles PepperoniButton.Click
pizza = New Pepperoni(pizza)
MargheritaBox.AppendText(pizza.getDescription() & vbNewLine)
End Sub
End Class
I assumed I could create a MargheritaPizza objcet with Button1 click and assign a pizza object to pizza via it's factory method createPizza
then on cheeseButton click I could wrap the pizza object created with the call pizza = New Cheese(pizza)!! The cheese class encapsulates the extra topping for the pizza. I thought that I could then call cost on the original pizza object wiich would delegate the cost through the wrapped objects?? As in the Decorator Pattern.
Some screen shot of output below:
Here I clicked create pizza then calculate cost then extra cheese finally calculate cost, all seems well!
This time I also clicked extra cheese and calculate cost, but the cost is not delegating through the objects correctly!
Here I added several extra cheese and also show some output to the console window for the test, the console window shows the size of the pizza each time the object is wrapped and shows that pizza size is 0 except on the inner most wrapper...What am I doing wrong??
My first language is Java and have no problem with this technique in the past, but new to VB 2013 and appreciate some help here..
All constructive comments welcome.
Many thanks
Please ignore code that's been commented out during testing
Wrapping
Firstly, and this is only my opinion, the term wrapping are used when you're dealing with NotInheritable classes.
Example:
Public Class String2
Public Sub New(s As String)
Me.s = s
End Sub
Default Public ReadOnly Property Chars(index As Integer) As Char
Get
Return Me.s.Chars(index)
End Get
End Property
Public ReadOnly Property Length() As Integer
Get
Return s.Length
End Get
End Property
Private ReadOnly s As String
End Class
Base classes
Secondly, you're overcomplicating this. The following code are stripped to make it more readable. Note that this is not a final solution.
Start by defining a Crust and a Size enum.
Public Enum PizzaCrust As Integer
[Default] = 0
DeepPan = 1
End Enum
Public Enum PizzaSize As Integer
S = 0
M = 1
L = 2
XL = 3
End Enum
You only need two base classes, Pizza and Extra.
Public MustInherit Class Pizza
Public Property Crust() As PizzaCrust
MustOverride ReadOnly Property Description() As String
Public ReadOnly Property Extras() As List(Of Extra)
MustOverride ReadOnly Property Name() As String
Public Property Size() As PizzaSize
Public Function CalculateCost() As Decimal
Dim value As Decimal = Me.GetBaseCost(Me.Size)
For Each extr As Extra In Me.Extras
value += extr.Cost
Next
Return value
End Function
Protected MustOverride Function GetBaseCost(size As PizzaSize) As Decimal
End Class
Public MustInherit Class Extra
Public MustOverride ReadOnly Property Name() As String
Public MustOverride ReadOnly Property Description() As String
Public MustOverride ReadOnly Property Cost() As Decimal
End Class
Pizzas
Create a namespace named Pizzas and put all of your pizzas here.
Namespace Pizzas
Public Class Margarita
Inherits Pizza
Public Overrides ReadOnly Property Description() As String
Public Overrides ReadOnly Property Name() As String
Protected Overrides Function GetBaseCost(size As PizzaSize) As Decimal
Select Case size
Case PizzaSize.S
Return 10
Case PizzaSize.M
Return 15
Case PizzaSize.L
Return 20
Case PizzaSize.XL
Return 30
Case Else
Return 0
End Select
End Function
End Class
Public Class Quattro
Inherits Pizza
Public Overrides ReadOnly Property Description() As String
Public Overrides ReadOnly Property Name() As String
Protected Overrides Function GetBaseCost(size As PizzaSize) As Decimal
End Class
End Namespace
Extras
Finally, create a namespace named Extras and put all of the extras here.
Namespace Extras
Public Class Cheese
Inherits Extra
Public Overrides ReadOnly Property Cost() As Decimal
Public Overrides ReadOnly Property Description() As String
Public Overrides ReadOnly Property Name() As String
End Class
Public Class Ham
Inherits Extra
Public Overrides ReadOnly Property Cost() As Decimal
Public Overrides ReadOnly Property Description() As String
Public Overrides ReadOnly Property Name() As String
End Class
Public Class Pineapple
Inherits Extra
Public Overrides ReadOnly Property Cost() As Decimal
Public Overrides ReadOnly Property Description() As String
Public Overrides ReadOnly Property Name() As String
End Class
End Namespace
Usage
Now, to create a new Margarita pizza, one would do it like this:
Dim pizza As New Pizzas.Margarita()
pizza.Size = PizzaSize.L
pizza.Crust = PizzaCrust.DeepPan
pizza.Extras.Add(New Extras.Ham())
pizza.Extras.Add(New Extras.Cheese())
I'm new to programming, OOP and Unit Test so please forgive me for my lack of knowledge.
As part of my Rock, Paper and Scissors game I have a abstract superclass (Weapon) which has subclasses (Rock, Paper and Scissors) in VB.NET like:
Public MustInherit Class Weapons
Public MustOverride Function compareTo(ByVal Weapons As Object) As Integer
End Class
Public Class Paper
Inherits Weapons
Public Overrides Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Paper Then
Return 0
ElseIf TypeOf Weapons Is Rock Then
Return 1
Else
Return -1
End If
End Function
End Class
Public Class Rock
Inherits Weapons
Public Overrides Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Rock Then
Return 0
ElseIf TypeOf Weapons Is Scissors Then
Return 1
Else
Return -1
End If
End Function
End Class
Public Class Scissors
Inherits Weapons
Public Overrides Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Scissors Then
Return 0
ElseIf TypeOf Weapons Is Paper Then
Return 1
Else
Return -1
End If
End Function
End Class
Also have a superclass Player which has subclasses (PlayerComputerRandom, PlayerHumanPlayer and PlayerComputerTactical) like:
Imports RockPaperScissors.Weapons
Public Class Player
Private pName As String
Private pNumberOfGamesWon As String
Public pWeapon As Weapons
Property Name() As String
Get
Return pName
End Get
Set(ByVal value As String)
pName = value
End Set
End Property
Property NumberOfGamesWon As String
Get
Return pNumberOfGamesWon
End Get
Set(ByVal value As String)
pNumberOfGamesWon = value
End Set
End Property
Property getWeapon As Weapons
Get
Return pWeapon
End Get
Set(ByVal value As Weapons)
pWeapon = value
End Set
End Property
Public Sub pickWeapon(ByVal WeaponType As String)
If WeaponType = "Rock" Then
pWeapon = New Rock()
ElseIf WeaponType = "Paper" Then
pWeapon = New Paper()
Else
pWeapon = New Scissors()
End If
End Sub
End Class
Imports RockPaperScissors.Weapons
Public Class PlayerComputerRandom
Inherits Player
Private Enum weaponsList
Rock
Paper
Scissors
End Enum
Public Overloads Sub pickWeapon()
Dim randomChoice = New Random()
Dim CompChoice As Integer = randomChoice.Next(0, [Enum].GetValues(GetType(weaponsList)).Length)
If CompChoice = "0" Then
pWeapon = New Rock()
ElseIf CompChoice = "1" Then
pWeapon = New Paper()
Else
pWeapon = New Scissors()
End If
End Sub
End Class
Public Class PlayerComputerTactical
Inherits Player
Private plastMove As String
Property lastMove() As String
Get
Return plastMove
End Get
Set(ByVal value As String)
plastMove = value
End Set
End Property
Public Overloads Sub pickWeapon()
' Add tactical player functionality
End Sub
End Class
Public Class PlayerHumanPlayer
Inherits Player
End Class
I have the GameForm class which instantiates the objects and performs various other logic used for the front-end as shown below:
Public Class GameForm
Private Sub btnRock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRock.Click
findWinner("HumanPlayer", "Rock", "RandomComputer")
End Sub
Private Sub btnPaper_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPaper.Click
findWinner("HumanPlayer", "Paper", "RandomComputer")
End Sub
Private Sub btnScissors_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnScissors.Click
findWinner("HumanPlayer", "Scissors", "RandomComputer")
End Sub
Public Sub findWinner(ByVal p1name As String, ByVal p1WeaponSelected As String, ByVal p2Name As String)
Dim player1 = New PlayerHumanPlayer()
Dim player2 = New PlayerComputerRandom()
player1.Name = p1name
player1.pickWeapon(p1WeaponSelected) ' Should I be using the Rock Class???
player2.Name = p2Name
player2.pickWeapon()
Dim winner As Integer = player1.getWeapon().compareTo(player2.getWeapon())
Select Case winner
Case 1
txtGameStatus.Text = player1.Name() + " wins!"
Case -1
txtGameStatus.Text = player2.Name() + " wins!"
Case 0
txtGameStatus.Text = "Draw!"
End Select
End Sub
End Class
I need to write unit tests of this using visual studio 2010. As I have never done this, I don't know what unit tests I could include (apart from the stand adding/substract examples). Could someone kindly provide a few unit tests to get started. It will give me a starting point.
Any help would be greatly appreciated.
Manys thanks in advance
My first tip would be to change all of your methods into functions which return a value, this is for the methods you want to unit test. Doing this will ensure that you can use the function for a unit test.
I can give you help for the structure, but I'm afraid I wont be doing your unit tests for you!
Ill show you an example unit test which I have in a solution, it may not be relevant to your solution but the structure is there nevertheless. First off I have the function (add) which i would like to test, and in a unit test project i have the test.
Function to test
Public Function Add(value1 As Int32, value2 As Int32)
answer = value1 + value2
Return answer
End Function
This is the unit test I am using within my unit test class
<TestMethod()> _
Public Sub AddTest()
Dim target As Form1 = New Form1()
Dim value1 As Int32 = 10
Dim value2 As Int32 = 35
Dim actual As Int32 = 45
Dim result As Int32 = target.Add(value1, value2)
Assert.AreEqual(result, actual)
End Sub
To try to give you an example of how you might structure this:
First of all, instead of this:
Public Overloads Sub pickWeapon()
' Logic...
End Sub
You might want to do something like this:
Public Overloads Function pickWeapon() as Weapons
Dim selectedWeapon as Weapons = Nothing;
// logic to set weapon here
return selectedWeapon;
End Sub
Now you can call that from a UnitTest, and make sure it returns an object which is a valid Weapon, for instance (not necessarily the most useful test, but hopefully, you get the point! :) ).
If your restructure the method findWinner() in a similar way, you can test that the logic of that method finds the correct winner.
Note however, that you should separate the logic for finding a winner from the weapon-picking. That is, you should create the players outside of that method, and pass them in to findWinner(). This will let you pass in certain options (weapons), and check that you get the expected result. You can't do that at the moment, since the weapon "player2" will use is selected by random inside findWinner().
Start by changing it so it will have a signature similar to the following:
' Takes two players in, and returns the name of the winner
Public Sub findWinner(ByVal humanPlayer As PlayerHumanPlayer,
ByVal computerPlayer As PlayerComputerRandom) As String
A (very simple) test, assuming you've rewritten the code to fit this:
<TestMethod()> _
Public Sub ShouldReturnPlayer1AsWinner()
Dim player1 = New PlayerHumanPlayer("Human name", New Scissors())
Dim player2 = New PlayerComputerRandom("Computer", New Rock())
Dim result As String = findWinner(player1, player2)
Assert.AreEqual(result, "Computer")
End Sub
Again, this may not be the be the best test, but it should give you an idea, and help you get started.
Sidenote: I would call the super-class Weapon, not Weapons. Think of it this way: You can have many many different instances of it, and they can be different weapons (paper, scissor, etc), but each is still a single weapon.