I am creating a VB 2008 change calculator as an assignment. The program is to use the amount paid - the amount due to calculate the total.(this is working fine). After that, it is to break that amount down into dollars, quarters, dimes, nickels, and pennies. The problem I am having is that sometimes the quantity of pennies, nickels or dimes will be a negative number. For example $2.99 = 3 Dollars and -1 Pennies.
SOLVED
Thanks to the responses, here is what I was able to make work with my limited knowledge.
Option Explicit On
Option Strict Off
Option Infer Off
Public Class frmMain
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'Clear boxes
lblDollarsAmount.Text = String.Empty
lblQuartersAmount.Text = String.Empty
lblDimesAmount.Text = String.Empty
lblNickelsAmount.Text = String.Empty
lblPenniesAmount.Text = String.Empty
txtOwed.Text = String.Empty
txtPaid.Text = String.Empty
lblAmountDue.Text = String.Empty
txtOwed.Focus()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
'Close application'
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
' Find Difference between Total Price and Total Received
lblAmountDue.Text = Val(txtPaid.Text) - Val(txtOwed.Text)
Dim intChangeAmount As Integer = lblAmountDue.Text * 100
'Declare Integers
Dim intDollarsBack As Integer
Dim intQuartersBack As Integer
Dim intDimesBack As Integer
Dim intNickelsBack As Integer
Dim intPenniesBack As Integer
' Change Values
Const intDollarValue As Integer = 100
Const intQuarterValue As Integer = 25
Const intDimeValue As Integer = 10
Const intNickelValue As Integer = 5
Const intPennyValue As Integer = 1
'Dollars
intDollarsBack = CInt(Val(intChangeAmount \ intDollarValue))
intChangeAmount = intChangeAmount - Val(Val(intDollarsBack) * intDollarValue)
lblDollarsAmount.Text = intDollarsBack.ToString
'Quarters
intQuartersBack = CInt(Val(intChangeAmount \ intQuarterValue))
intChangeAmount = intChangeAmount - Val(Val(intQuartersBack) * intQuarterValue)
lblQuartersAmount.Text = intQuartersBack.ToString
'Dimes
intDimesBack = CInt(Val(intChangeAmount \ intDimeValue))
intChangeAmount = intChangeAmount - Val(Val(intDimesBack) * intDimeValue)
lblDimesAmount.Text = intDimesBack.ToString
'Nickels
intNickelsBack = CInt(Val(intChangeAmount \ intNickelValue))
intChangeAmount = intChangeAmount - Val(Val(intNickelsBack) * intNickelValue)
lblNickelsAmount.Text = intNickelsBack.ToString
'Pennies
intPenniesBack = CInt(Val(intChangeAmount \ intPennyValue))
intChangeAmount = intChangeAmount - Val(Val(intPenniesBack) * intPennyValue)
lblPenniesAmount.Text = intPenniesBack.ToString
End Sub
End Class
In your example of $2.99, look at where you calculate inDollarsBack. You are obviously getting a value of 3, when you need 2. Without giving it away, think of possible reasons why dividing 2.99 by 1 would produce a value of 3.
You can use the following change calculator and then update the UI.
Imports System.Collections.Generic
Imports System.Linq
Imports Microsoft.VisualBasic
Public Class ChangeCalculator
Private denominations As List(Of Denomination)
Public Sub New()
Me.denominations = New List(Of Denomination)
With Me.denominations
.Add(New Denomination With {.Value = 1D})
.Add(New Denomination With {.Value = 0.25D})
.Add(New Denomination With {.Value = 0.1D})
.Add(New Denomination With {.Value = 0.05D})
.Add(New Denomination With {.Value = 0.01D})
End With
End Sub
Public Sub Calculate(ByVal change As Decimal)
Me.ResetDenominationUnits()
Dim remainingChange = change
For Each denomination In (From d In Me.denominations
Order By d.Value Descending
)
If remainingChange > denomination.Value Then
denomination.Units = CInt(
Conversion.Int(remainingChange / denomination.Value)
)
remainingChange -= denomination.Value * denomination.Units
End If
Next
End Sub
Public ReadOnly Property Dollars As Integer
Get
Return Me.GetUnits(1D)
End Get
End Property
Public ReadOnly Property Quarters As Integer
Get
Return Me.GetUnits(0.25D)
End Get
End Property
Public ReadOnly Property Dimes As Integer
Get
Return Me.GetUnits(0.1D)
End Get
End Property
Public ReadOnly Property Nickels As Integer
Get
Return Me.GetUnits(0.05D)
End Get
End Property
Public ReadOnly Property Pennies As Integer
Get
Return Me.GetUnits(0.01D)
End Get
End Property
Private Function GetUnits(ByVal denomination As Decimal) As Integer
Return (From d In Me.denominations
Where d.Value = denomination
).Single().Units
End Function
Private Sub ResetDenominationUnits()
For Each denomination In Me.denominations
denomination.Units = 0
Next
End Sub
End Class
Public Class Denomination
Public Property Value As Decimal
Public Property Units As Integer
End Class
Inasmuch as my answer's similar to Tim Murphy's, I think this one's more straight forward and you don't need to update the UI.
Module Module1
Sub Main()
Console.WriteLine("Enter the amount of change or type EXIT to close.")
Dim input = Console.ReadLine
Do While input.ToUpper.Trim <> "EXIT"
Dim c = GetChange(CDec(Val(input)))
Console.WriteLine("{0} dollars, {1} quarters, {2} dimes, {3} nickels and {4} pennies", _
c.Dollars, c.Quarters, c.Dimes, c.Nickels, c.Pennies)
Console.WriteLine(vbCrLf & vbCrLf & "Enter the amount of change or type EXIT to quit.")
input = Console.ReadLine
Loop
End Sub
Public Function GetChange(ByVal change As Decimal) As Change
Dim denominations = New Decimal() {1D, 0.25D, 0.1D, 0.05D, 0.01D}
Dim c(4) As Integer
For i = 0 To denominations.Length - 1
If change >= denominations(i) Then
c(i) = CInt(Conversion.Int(change / denominations(i)))
change -= (c(i) * denominations(i))
End If
Next
Dim r As New Change
With r
.Dollars = c(0)
.Quarters = c(1)
.Dimes = c(2)
.Nickels = c(3)
.Pennies = c(4)
End With
Return r
End Function
Public Structure Change
Dim _dollars As Integer
Dim _quarters As Integer
Dim _nickels As Integer
Dim _dimes As Integer
Dim _pennies As Integer
Public Property Dollars() As Integer
Get
Return _dollars
End Get
Set(ByVal value As Integer)
_dollars = value
End Set
End Property
Public Property Quarters() As Integer
Get
Return _quarters
End Get
Set(ByVal value As Integer)
_quarters = value
End Set
End Property
Public Property Dimes() As Integer
Get
Return _dimes
End Get
Set(ByVal value As Integer)
_dimes = value
End Set
End Property
Public Property Nickels() As Integer
Get
Return _nickels
End Get
Set(ByVal value As Integer)
_nickels = value
End Set
End Property
Public Property Pennies() As Integer
Get
Return _pennies
End Get
Set(ByVal value As Integer)
_pennies = value
End Set
End Property
End Structure
End Module
Public Shared Function CalculateChange(ByVal dblDollarsPaid As Double, ByVal dblDollarsOwed As Double)
Dim intChangeCents As Integer
Dim change As New Change()
intChangeCents = CInt((dblDollarsPaid - dblDollarsOwed) * 100)
change.Dollars = intChangeCents \ 100
intChangeCents = intChangeCents Mod 100
change.Quarters = intChangeCents \ 25
intChangeCents = intChangeCents Mod 25
change.Dimes = intChangeCents \ 10
intChangeCents = intChangeCents Mod 10
change.Nickels = intChangeCents \ 5
intChangeCents = intChangeCents Mod 5
change.Pennies = intChangeCents
Return change
End Function
Usage:
Dim c As Change
c = CalculateChange(13.26, 2.99)
Console.WriteLine("{0} dollars, {1} quarters, {2} dimes, {3} nickels and {4} pennies", _
c.Dollars, c.Quarters, c.Dimes, c.Nickels, c.Pennies)
\ is the operator for integer division, e.g. 5 \ 2 is 2, not 2.5.
The Change structure is from Alex Essilfie's answer.
Quite Simply, here it is. To solve the negative change, remove all Options except Explicit
Option Explicit On
Public Class frmMoneyChange
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
lblFivesAmount.Text = String.Empty
lblTensAmount.Text = String.Empty
lblDollarsAmount.Text = String.Empty
lblQuartersAmount.Text = String.Empty
lblDimesAmount.Text = String.Empty
lblNickelsAmount.Text = String.Empty
lblPenniesAmount.Text = String.Empty
txtOwed.Text = String.Empty
txtPaid.Text = String.Empty
lblAmountDue.Text = String.Empty
txtOwed.Focus()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim decChangeAmount As Decimal
Dim intDollarsBack As Integer
Dim intQuartersBack As Integer
Dim intDimesBack As Integer
Dim intNickelsBack As Integer
Dim intPenniesBack As Integer
Dim decPaid As Decimal
Dim decOwed As Decimal
Const intFiveDollarValue As Integer = 5
Const intTenDollarValue As Integer = 10
Const intDollarValue As Integer = 1
Const decQuarterValue As Decimal = 0.25
Const decDimeValue As Decimal = 0.1
Const decNickelValue As Decimal = 0.05
Const decPennyValue As Decimal = 0.01
decOwed = Convert.ToDecimal(txtOwed.Text)
decPaid = Convert.ToDecimal(txtPaid.Text)
decChangeAmount = decPaid - decOwed
lblAmountDue.Text = decChangeAmount.ToString("C")
'Ten Dollars
intDollarsBack = (decChangeAmount * 100 \ intTenDollarValue * 100)
decChangeAmount = decChangeAmount - (intDollarsBack) * intTenDollarValue
lblTensAmount.Text = intDollarsBack.ToString
'Five Dollars
intDollarsBack = (decChangeAmount * 100 \ intFiveDollarValue * 100)
decChangeAmount = decChangeAmount - (intDollarsBack) * intFiveDollarValue
lblFivesAmount.Text = intDollarsBack.ToString
'Dollars
intDollarsBack = (decChangeAmount * 100 \ intDollarValue * 100)
decChangeAmount = decChangeAmount - (intDollarsBack) * intDollarValue
lblDollarsAmount.Text = intDollarsBack.ToString
'Quarters
intQuartersBack = (decChangeAmount * 100 \ decQuarterValue * 100)
decChangeAmount = decChangeAmount - (intQuartersBack) * decQuarterValue
lblQuartersAmount.Text = intQuartersBack.ToString()
'Dimes
intDimesBack = (decChangeAmount * 100 \ decDimeValue * 100)
decChangeAmount = decChangeAmount - (intDimesBack) * decDimeValue
lblDimesAmount.Text = intDimesBack.ToString
'Nickels
intNickelsBack = (decChangeAmount * 100 \ decNickelValue * 100)
decChangeAmount = decChangeAmount - (intNickelsBack) * decNickelValue
lblNickelsAmount.Text = intNickelsBack.ToString
'Pennies
intPenniesBack = (decChangeAmount * 100 \ decPennyValue * 100)
decChangeAmount = decChangeAmount - (intPenniesBack) * decPennyValue
lblPenniesAmount.Text = intPenniesBack.ToString
End Sub
End Class
Related
I am making a Math quiz game and I wondering why the question does not change to a NEW ONE when I get the right answer and HOW to make it to 10 and stop running then jump out a message box to ask the user want to PLAY AGAIN or not?
Public Class Multiplication
Dim TotalQuestion As Integer
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim numOne As Integer = R.Next(0, 10)
Dim numTwo As Integer = R.Next(1, 10)
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = numOne & " x " & numTwo & " = "
lblQuestionMUL.Text = Show
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Return num1 * num2
Generate()
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, numOne & numTwo)
Ans = Multiply(numOne, numTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
Generate()
End Sub
End Class
In addition to previous comments you should set the numOne and numTwo variables to random numbers in Generate Sub (Keeping the declaration as Global Variables). Your code just set them in the beginning to random numbers only once. Check the code below:
Public Class Multiplication
Dim TotalQuestion As Integer = 0
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim NumOne As Integer
Dim NumTwo As Integer
Dim QuizCompleted As Boolean = False
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
If TotalQuestion < 10 Then
NumOne = R.Next(0, 10)
NumTwo = R.Next(1, 10)
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = NumOne & " x " & NumTwo & " = "
lblQuestionMUL.Text = Show
Else
QuizCompleted = True
End If
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Generate()
Return num1 * num2
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, NumOne & NumTwo)
Ans = Multiply(NumOne, NumTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
If QuizCompleted Then
MsgBox("Quiz Completed")
End If
End Sub
End Class
Here's the image of my design interface:Design Interface
I want the user to make a selection and enter the quantity they wish to purchase then once they are done and press calculate, it gives the total of the items selected according to the quantity entered and inputs that total in the price textboxes.
Here's my code...
I am stuck...
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Public Sub frmDrinks_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim tMango As Integer
Dim tOrange As Integer
Dim tStrawberry As Integer
Dim tWatermelon As Integer
Dim tMinty As Integer
Dim tCoke As Integer
Dim tDiet As Integer
Dim tSprite As Integer
Dim tMineral As Integer
Dim tSpark As Integer
Dim tManSmooth As Integer
Dim tBanSmooth As Integer
Dim tTropSmooth As Integer
Dim tStrawSmooth As Integer
Dim tVanilla As Integer
Dim tCookie As Integer
Dim tManShake As Integer
Dim tBanShake As Integer
tMango = txtMango.Text
tOrange = txtOrange.Text
tStrawberry = txtStrawberry.Text
tWatermelon = txtWatermelon.Text
tMinty = txtMinty.Text
tCoke = txtCoke.Text
tDiet = txtDiet.Text
tSprite = txtSprite.Text
tMineral = txtMineral.Text
tSpark = txtSparkling.Text
tManSmooth = txtMansmooth.Text
tBanSmooth = txtBanana.Text
tTropSmooth = txtTropical.Text
tStrawSmooth = txtStrawSmooth.Text
tVanilla = txtVanilla.Text
tCookie = txtChipCookie.Text
tManShake = txtManShake.Text
tBanShake = txtBanShake.Text
Dim TotalSum As Double = 0
If Me.chkJuices.Items().ToString = "Mango" Then
TotalSum += (100 * tMango)
End If
If Me.chkJuices.Items().ToString = "Orange" Then
TotalSum += (100 * tOrange)
End If
If Me.chkJuices.Items().ToString = "Strawberry" Then
TotalSum += (100 * tStrawberry)
End If
If Me.chkJuices.Items().ToString = "Watermelonade" Then
TotalSum += (100 * tWatermelon)
End If
If Me.chkJuices.Items().ToString = "Minty Pineade" Then
TotalSum += (100 * tMinty)
End If
txtJuice.Text = TotalSum
End Sub
On the button click you will have to look after the checkboxes that are checked and then do the proper math
Private Sub Calculate() Handles Button.click
Dim TotalSum As Double = 0
For i = 0 To (CheckedListBox1.Items.Count - 1)
If CheckedListBox1.GetItemChecked(i) = True Then
If CheckedListBox1.Items(i).ToString = "Mango" Then
TotalSum += (100 * tMango)
End If
If CheckedListBox1.Items(i).ToString = "Orange" Then
TotalSum += (100 * tOrange)
End If
End If
Next
End Sub
I'm working on a school project using VIsual Studio 2015, the assignment is to create GUI "Commute Calculator" with three options for mode of transportation. I've wrote the code following the instructions in my textbook but am getting the following error:
"BC30057 Too many arguments to 'Private Function CarFindCost(intCommuteChoice As Integer, intDays As Integer) As Decimal'."
I'm a newbie to vs, but based on the error I believe the problem is with how I declared variables. I googled how to convert an integer to decimal, but haven't found anything that worked. The code is lengthy, but I included it all as an FYI. The error is in the private sub btnCommute and appears to be tied to three private functions: CarFindCost, BusFindCost and TrainFindCost. How to I fix it so I don't get errors on the variable intLength in the private sub bthCommute?
Option Strict On
Public Class frmCommuteCalc
Dim intCommuteChoice As Integer
Dim strSelectedMode As String = ""
Private _strGas As Integer
Private _strMiles As String = "Enter the total miles for a round trip: "
Private _strMilesPerGallon As Double = 2.15
Private _strDailyParking As Decimal = 10
Private _strMonthlyParking As Decimal
Private _strMonthlyUpkeep As Decimal = 112
Private _strRTBusFare As String = "Round trip bus fare is "
Private _strRTTrainFare As String = "Round trip train fare is "
Private _StrDays As String = "Enter the number of days worked per month: "
Private _intTrainFare As Integer
Private Sub frmCommuteCalc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Threading.Thread.Sleep(5000)
End Sub
Private Sub cboCommuteMethod_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCommuteMethod.SelectedIndexChanged
Dim intCommuteChoice As Integer
intCommuteChoice = cboCommuteMethod.SelectedIndex()
lstCommute.Items.Clear()
Select Case intCommuteChoice
Case 0
Car()
Case 1
Train()
Case 2
Bus()
End Select
lblDays.Visible = True
lblMiles.Visible = True
lblLength.Visible = True
txtDays.Visible = True
'txtMonthlyTotal.Visible = True
End Sub
Private Sub btnCompute_Click(sender As Object, e As EventArgs) Handles btnCompute.Click
Dim intCommuteChoice As Integer
Dim intDaysPerMonth As Integer
Dim decTotalCost As Decimal
Dim intLength As Integer = 0
Dim strSelectedMode As String = ""
Dim blnNumberInDaysIsValid As Boolean = False
Dim blnCommuteMethodIsSelected As Boolean = False
blnNumberInDaysIsValid = ValidateNumberInDays()
intCommuteChoice = ValidateCommuteSelection(blnCommuteMethodIsSelected, strSelectedMode)
If (blnNumberInDaysIsValid And blnCommuteMethodIsSelected) Then
intDaysPerMonth = Convert.ToInt32(txtDays.Text)
intCommuteChoice = cboCommuteMethod.SelectedIndex()
Select Case intCommuteChoice
Case 0
decTotalCost = CarFindCost(intCommuteChoice, intDaysPerMonth, intLength)
Case 1
decTotalCost = BusFindCost(intCommuteChoice, intDaysPerMonth, intLength)
Case 2
decTotalCost = TrainFindCost(intCommuteChoice, intDaysPerMonth, intLength)
End Select
End If
End Sub
Private Function intLength() As Object
Throw New NotImplementedException()
End Function
Function ComputeCommuteCost(ByVal decMiles As Decimal, ByVal decGallons As Decimal) As Decimal
Dim decMilage As Decimal
decMilage = decMiles / decGallons
Return decMilage
End Function
Private Sub Car()
lstCommute.Items.Add(_strMiles)
lstCommute.Items.Add(_strMilesPerGallon)
lstCommute.Items.Add(_StrDays)
lstCommute.Items.Add(_strMonthlyParking)
lstCommute.Items.Add(_strMonthlyUpkeep)
End Sub
Private Sub Bus()
lstCommute.Items.Add(_strRTBusFare)
lstCommute.Items.Add(_StrDays)
End Sub
Private Sub Train()
lstCommute.Items.Add(_StrDays)
lstCommute.Items.Add(_strRTTrainFare)
End Sub
Private Function ValidateNumberInDays() As Boolean
Dim intDays As Integer
Dim blnValidityCheck As Boolean = False
Dim strNumberInDaysMessage As String = "Please enter the No. of days per month you will be commuting "
Dim strMessageBoxTitle As String = "Error"
Try
intDays = Convert.ToInt32(txtDays.Text)
If intDays >= 1 And intDays <= 21 Then
blnValidityCheck = True
Else
MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
txtDays.Focus()
txtDays.Clear()
End If
Catch Exception As FormatException
MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
txtDays.Focus()
txtDays.Clear()
Catch Exception As OverflowException
MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
txtDays.Focus()
txtDays.Clear()
Catch Exception As SystemException
MsgBox(strNumberInDaysMessage, , strMessageBoxTitle)
txtDays.Focus()
txtDays.Clear()
End Try
Return blnValidityCheck
End Function
Private Function ValidateCommuteSelection(ByRef blnDays As Boolean, ByRef strDays As String) As Integer
Dim intCommuteChoice As Integer
Try
intCommuteChoice = Convert.ToInt32(lstCommute.SelectedIndex)
strDays = lstCommute.SelectedItem.ToString()
blnDays = True
Catch Exception As SystemException
MsgBox("Select a commute mode", , "Error")
blnDays = False
End Try
Return intCommuteChoice
End Function
Private Function CarFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal
Dim decDaysPerMonth As Decimal
Dim decMiles As Decimal
Dim decMilesPerGallon As Decimal = 2
Dim decGasTotal As Decimal
Dim decDailyParking As Decimal = 10
Dim decMonthlyParking As Decimal
Dim decMonthlyUpkeep As Decimal = 112
Dim decFinalCost As Decimal
Dim intLength As Integer = 0
decMiles = Convert.ToDecimal(txtMiles.Text)
decMilesPerGallon = Convert.ToDecimal(txtGallons.Text)
decGasTotal = decMilesPerGallon * decMiles
decMonthlyParking = Convert.ToDecimal(lblLength.Text)
decMonthlyParking = decDailyParking * decDaysPerMonth
decFinalCost = Convert.ToDecimal(lblLength.Text)
decFinalCost = decGasTotal + decMonthlyUpkeep + decMonthlyParking
Return decFinalCost
End Function
Private Function BusFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal
Dim intLength As Integer = 0
Dim decDaysPerMonth As Decimal
Dim decBusFarePerDay As Decimal = 4
Dim decFinalCost As Decimal
decBusFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
decFinalCost = decBusFarePerDay * decDaysPerMonth
Return decFinalCost
End Function
Private Function TrainFindCost(ByVal intCommuteChoice As Integer, ByVal intDays As Integer) As Decimal
Dim intLength As Integer = 0
Dim decDaysPerMonth As Decimal
Dim decTrainFarePerDay As Decimal = 18
Dim decFinalCost As Decimal
decTrainFarePerDay = Convert.ToDecimal(txtMonthlyTotal)
decFinalCost = Convert.ToDecimal(txtMonthlyTotal)
decFinalCost = decDaysPerMonth * decTrainFarePerDay
Return decFinalCost
End Function
End Class
In:
Select Case intCommuteChoice ... End Select
in each case; call function CarFindCost with 3 parameters y you have declared with only 2.
Ever since I added the CheckForCollision_Enemy method, I've been getting a stack overflow exception every time I run my code.
Here is the CheckForCollision_Enemy method, in the Main class.
Public Sub CheckForCollision_Enemy()
Dim ship1 As New Enemy(Nothing, Nothing)
Dim ship2 As New Enemy(Nothing, Nothing)
Debug.Print("")
Dim ships = {acc_e, bs_e, sb_e, ds_e, pb_e}
For i As Integer = 0 To ships.Length - 1
ship1 = ships(i)
For j As Integer = 0 To ships.Length - 1
ship2 = ships(j)
If ship1.name <> ship2.name Then
For l As Integer = 0 To ship1.length - 1
For t As Integer = 0 To ship2.length - 1
If ship1.space_filled(l, 0) = ship2.space_filled(t, 0) And ship1.space_filled(l, 1) = ship2.space_filled(t, 1) Then
Debug.Print("Collision at {" & ship1.space_filled(l, 0) & ", " & ship1.space_filled(l, 1) & "} " & ship1.name & " VS " & ship2.name)
End If
Next
Next
End If
Next
Next
End Sub
Here is the Enemy class. This is the class where the error is shown. I marked exactly where as a comment.
Shared gen As New Random()
Dim x As Integer = 0
Dim y As Integer = 0
Public Sub New(ByVal namep As String, ByVal lengthp As Integer)
name = namep
length = lengthp
ReDim _start_point(2)
ReDim _space_filled(length, 2)
GenerateDirection()
If direction = "horizontal" Then
x = gen.Next(0, 11 - length)
y = gen.Next(0, 10)
ElseIf direction = "vertical" Then
x = gen.Next(0, 10)
y = gen.Next(0, 11 - length)
End If
GenerateStartPoint()
ExtendStartPoint()
DefineFilled()
ColorFilled()
Main.CheckForCollision_Enemy() 'If this is taken out, it will work fine.
End Sub
Public Sub GenerateStartPoint()
start_point = {x, y}
End Sub
Public Sub GenerateDirection()
If gen.Next(0, 2) = 0 Then
direction = "horizontal"
Else
direction = "vertical"
End If
End Sub
Public Sub ExtendStartPoint()
If direction = "horizontal" Then
For i As Integer = 0 To length - 1
space_filled(i, 0) = start_point(0) + i
space_filled(i, 1) = start_point(1)
Next
ElseIf direction = "vertical" Then
For i As Integer = 0 To length - 1
space_filled(i, 0) = start_point(0)
space_filled(i, 1) = start_point(1) + i
Next
End If
End Sub
Public Sub DefineFilled()
For i As Integer = 0 To length - 1
x = space_filled(i, 0)
y = space_filled(i, 1)
Try
generate = False
Main.TrackerBoard.box_list(x, y).full = True
Catch
End Try
Next
End Sub
Private Sub ColorFilled()
For y As Integer = 0 To 9
For x As Integer = 0 To 9
'Debug.Print(Main.PlayerBoard.box_list(x, y).full)
If Main.TrackerBoard.box_list(x, y).full = True Then 'New error: "InvalidOperationException"
Main.TrackerBoard.box_list(x, y).image.BackColor = System.Drawing.Color.Red
Else
Main.TrackerBoard.box_list(x, y).image.BackColor = System.Drawing.Color.Silver 'Most often, the error appears here.
End If
Next
Next
End Sub
Here is the ship class. I've taken out most of the methods to save space; if you want to see anything, I'll add it in for you.
Public Class Ship
Dim _name As String
Public Property name() As String ...
Dim WithEvents _image As PictureBox
Public Property image() As PictureBox ...
Dim _length As Integer
Public Property length() As Integer ...
Dim _direction As String
Public Property direction() As String ...
Dim _selected As Boolean
Public Property selected() As Boolean ...
Dim _placed As Boolean
Public Property placed() As Boolean ...
Dim _location() As Integer = {0, 0}
Public Property location() As Integer() ...
Dim _has_moved As Boolean
Public Property has_moved() As Boolean ...
Dim _space_filled(,) As Integer
Public Property space_filled() As Integer(,) ...
Public rect As System.Drawing.Rectangle
Dim mouse_up As Boolean = False
Dim tile_size As Integer = 25
Public Sub New(ByVal namep As String, ByVal imagep As PictureBox, ByVal lengthp As Integer, ByVal directionp As String, ByVal selectedp As Boolean, ByVal placedp As Boolean)
name = namep
image = imagep
length = lengthp
direction = directionp
selected = selectedp
placed = placedp
location(0) = 0
location(1) = 0
ReDim space_filled(length, 2)
rect = New System.Drawing.Rectangle(location(0), location(1), length * tile_size, 1 * tile_size)
End Sub
Private Sub Ship_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseMove ...
Private Sub Ships_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseClick ...
Private Sub Ship_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _image.MouseUp ...
Public Sub Update() ...
Public Sub SnapToBox() ...
Private Sub DefineSpaceFilled() ...
Private Sub ColorFilled() ...
End Class
Your CheckForCollision_Enemy calls New Enemy, and New Enemy calls CheckForCollision_Enemy. You are recursing until the stack overflows.
I'm working on a visual basic application( w/ visual studio 2010) that calculates ticket sales. This one is been really challenging since i'm a newbie when it comes to visual basic.
I'm i'm having trouble getting the calculate button to
Here are the instruction to get the costs from the functions and use them to calculate the total. Here are the instructions they give me.
User selects whether to purchase season tickets or single-game tickets
User enters the number of tickets needed and the type of seats based on whether they selected season single-game tickets.
User clicks the Compute Ticket Cost Button to display final cost
User clicks the Clear Form button to clear the response
I'm stuck on the calculating button. I just need to be able to capture the cost from the button and then use the button to compute it.
Public Class Form1
'Global Variables
Dim intTicketChoice As Integer
Dim finalCost As Decimal
Dim cost As Decimal
Private Sub cboTicketType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTicketType.SelectedIndexChanged
intTicketChoice = Me.cboTicketType.SelectedIndex
Me.lstSeatType.Items.Clear()
Select Case intTicketChoice
Case 0 : SingleGame()
Case 1 : Seasonal()
End Select
'Make Items visible
Me.lblCostDisplay.Visible = True
Me.lblSeats.Visible = True
Me.lblTickets.Visible = True
Me.lstSeatType.Visible = True
Me.txtTicketNum.Visible = True
Me.btnClear.Visible = True
Me.btnCompute.Visible = True
Me.txtTicketNum.Focus()
End Sub
Private Sub SingleGame()
Dim seatType As Integer
'Add List Items
Me.lstSeatType.Items.Add("Box Seats $55")
Me.lstSeatType.Items.Add("Lower Deck Seats $35")
Me.lstSeatType.Items.Add("Upper Deck Seats $25")
Me.lstSeatType.Items.Add("Standing Room Only $15")
If lstSeatType.SelectedItem = "Box Seats $55" Then
seatType = 0
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $35" Then
seatType = 1
End If
If lstSeatType.SelectedItem = "Upper Deck Seats $25" Then
seatType = 2
End If
If lstSeatType.SelectedItem = "Standing Room Only $15" Then
seatType = 3
End If
End Sub
Private Sub Seasonal()
Dim seatType As Integer
'Add List Items
Me.lstSeatType.Items.Add("Box Seats $2500")
Me.lstSeatType.Items.Add("Lower Deck Seats $1500")
'Price Items for Single Games
If lstSeatType.SelectedItem = "Box Seats $2500" Then
seatType = 4
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $1500" Then
seatType = 5
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim ticketNum As Integer
Dim totalCost As Decimal
ticketNum = Convert.ToInt32(Me.txtTicketNum.Text)
intTicketChoice = Me.cboTicketType.SelectedIndex
Select Case intTicketChoice
Case 0 : totalCost = SingleGameCost()
Case 1 : totalCost = SeasonalCost()
End Select
'try and catch number textbox
Try
ticketNum = Convert.ToInt32(txtTicketNum.Text)
Catch Exception As FormatException
MsgBox("Number of tickets must be numeric")
Return
End Try
'display cost of tickets
Me.lblCostDisplay.Text = "The total cost of tickets purchased:" & totalCost.ToString("C")
End Sub
Private Function SingleGameCost(ByVal seatType As Integer, ByVal ticketNum As Integer)
finalCost = ticketNum * cost
'Price Items for Single Games
If seatType = 0 Then
cost = 55D
End If
If seatType = 1 Then
cost = 35D
End If
If seatType = 2 Then
cost = 25D
End If
If seatType = 3 Then
cost = 15D
End If
Return finalCost
End Function
Private Function SeasonalCost(ByVal seatType As Integer, ByVal ticketNum As Integer, ByRef cost As Decimal)
Dim finalCost As Decimal
If seatType = 4 Then
cost = 2500D
End If
If seatType = 0 Then
cost = 1500D
End If
finalCost = cost * ticketNum
Return finalCost
End Function
End Class
the error is happening here :
If intTicketChoice = 0 Then
SingleGameCost()
End If
If intTicketChoice = 1 Then
SeasonalCost()
End If
with the singlegamecost() function and the seasonacost() function.
You need to have the seatType as a Public Variable.
then once they select the Seat you set that Variable
and then use the variable when you are Computing.
Then return the Cost.
In the Compute Function
After you have got the final cost then
me.lblCostDisplay.Text = finalCost.ToString()
I have modified this a little for you. Take what you want from it.
I have not tested it. Hope this helps... Not sure why the formating
did not come out quite right..
Public Class Form1
Private SeatType As Integer = 0
Private Sub cboTicketType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTicketType.SelectedIndexChanged
Dim intTicketChoice As Integer = Me.cboTicketType.SelectedIndex
Me.lstSeatType.Items.Clear()
Select Case intTicketChoice
Case 0
Me.lstSeatType.Items.Add("Box Seats $55")
Me.lstSeatType.Items.Add("Lower Deck Seats $35")
Me.lstSeatType.Items.Add("Upper Deck Seats $25")
Me.lstSeatType.Items.Add("Standing Room Only $15")
Case 1
Me.lstSeatType.Items.Add("Box Seats $2500")
Me.lstSeatType.Items.Add("Lower Deck Seats $1500")
Case Else
End Select
'Make Items visible
Me.lblCostDisplay.Visible = True
Me.lblSeats.Visible = True
Me.lblTickets.Visible = True
Me.lstSeatType.Visible = True
Me.txtTicketNum.Visible = True
Me.btnClear.Visible = True
Me.btnCompute.Visible = True
Me.txtTicketNum.Focus()
End Sub
Private Sub lstSeatType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSeatType.SelectedIndexChanged
If lstSeatType.SelectedItem.ToString.ToLower = "box seats $55" Then
SeatType = 0
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "lower deck seats $35" Then
SeatType = 1
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "upper deck seats $25" Then
SeatType = 2
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "standing room only $15" Then
SeatType = 3
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "box seats $2500" Then
SeatType = 4
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "lower deck seats $1500" Then
SeatType = 5
End If
End Sub
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim sTicketNum As String = txtTicketNum.Text
If Not String.IsNullOrEmpty(sTicketNum) Then
Try
Dim ticketNum As Integer = Convert.ToInt32(Me.txtTicketNum.Text)
Dim totalCost As Decimal = GetGameCost(ticketNum)
'try and catch number textbox
Me.lblCostDisplay.Text = "The total cost of tickets purchased: " & totalCost.ToString("C")
Catch Exception As FormatException
MsgBox("Number of tickets must be numeric")
Return
End Try
'display cost of tickets
Else
MsgBox("Please input a ticket number.")
txtTicketNum.focus()
Return
End If
End Sub
Private Function GetGameCost(ByVal ticketNum As Integer) As Decimal
Dim finalCost As Decimal = 0
'Price Items for Single Games
Select Case SeatType
Case 0
finalCost = (ticketNum * 55D)
Case 1
finalCost = (ticketNum * 35D)
Case 2
finalCost = (ticketNum * 25D)
Case 3
finalCost = (ticketNum * 15D)
Case 4
finalCost = (ticketNum * 1500D)
Case 5
finalCost = (ticketNum * 2500D)
Case Else
End Select
'
Return finalCost
'
End Function
End Class
There are numerous issues with the above code. It needs heavy refactoring. But even without that, the question cannot be fully answered in the current form for the following reason - You are calling SingleGameCost and SeasonalCost without parameters, however they are declared with such.
This code would not compile. If it does compile at your side, there is some code you did include to support the question. If it does not compile, this is the answer.
Regarding refactoring, clauses like this:
If lstSeatType.SelectedItem = "Box Seats $55" Then
seatType = 0
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $35" Then
seatType = 1
End If
If lstSeatType.SelectedItem = "Upper Deck Seats $25" Then
seatType = 2
End If
If lstSeatType.SelectedItem = "Standing Room Only $15" Then
seatType = 3
End If
Can be rewritten:
Select Case lstSeatType.SelectedItem
Case "Box Seats $55" : seatType = 0
Case "Lower Deck Seats $35" : seatType = 1
Case "Upper Deck Seats $25" : seatType = 2
Case "Standing Room Only $15" : seatType = 3
End Select
Even though, as written, value of seatType would be lost, because it is declared as a local variable.
Strange. I'm getting no errors when I wrote the code, though I still have to write the Clear Code for it - but I'll go ahead and give the code I have at the moment.
Public Class BaseballTickets
Private _strBoxSeats As String = "Box Seats"
Private _strLowerDeck As String = "Lower Deck"
Private _strUpperDeck As String = "Upper Deck"
Private _strStandingRoomOnly As String = "Standing Room Only"
Private Sub lblBaseballTicketSales_Click(sender As System.Object, e As System.EventArgs) Handles lblBaseballTicketSales.Click
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub cboxTicketType_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboxTicketType.SelectedIndexChanged
Dim intTicketType As Integer
intTicketType = Me.cboxTicketType.SelectedIndex
lstSeatingType.Items.Clear()
Select Case intTicketType
Case 0
SeasonTickets()
Case 1
SingleGameTickets()
End Select
lblBaseballTicketSales.Visible = True
lblNumberOfGroup.Visible = True
lblTicketChoice.Visible = True
lblTicketCost.Visible = True
lblTicketCost.Text = ""
txtAmountOfPeople.Focus()
End Sub
Private Sub SeasonTickets()
lstSeatingType.Items.Add(_strBoxSeats)
lstSeatingType.Items.Add(_strLowerDeck)
End Sub
Private Sub SingleGameTickets()
lstSeatingType.Items.Add(_strBoxSeats)
lstSeatingType.Items.Add(_strLowerDeck)
lstSeatingType.Items.Add(_strStandingRoomOnly)
lstSeatingType.Items.Add(_strUpperDeck)
End Sub
Private Sub btnCost_Click(sender As System.Object, e As System.EventArgs) Handles btnCost.Click
Dim intGroupSize As Integer
Dim blnNumberInPartyIsValid As Boolean = False
Dim blnTicketIsSelected = False
Dim intTicketType As Integer
Dim strSelectedTicket As String = ""
Dim intTicketChoice As Integer
Dim decTotalCost As Decimal
blnNumberInPartyIsValid = ValidateNumberInParty()
intTicketChoice = ValidateTicketIsSelected(blnTicketIsSelected, strSelectedTicket)
If (blnNumberInPartyIsValid And blnTicketIsSelected) Then
intGroupSize = Convert.ToInt32(txtAmountOfPeople.Text)
intTicketType = Me.cboxTicketType.SelectedIndex
Select Case intTicketType
Case 0
decTotalCost = SeasonTicketsFindCost(intTicketType, _
intGroupSize)
Case 1
decTotalCost = SingleGameTicketsFindCost(intTicketType, _
intGroupSize)
End Select
lblTicketCost.Text = "The total cost of tickets purchased: " & decTotalCost.ToString("C")
End If
End Sub
Private Function ValidateNumberInParty() As Boolean
Dim intNumberOfPeople As Integer
Dim blnValidityCheck As Boolean = False
Dim strNumberInPartyErrorMessage As String = _
"Please Enter the Number of people Accompanying you (1-99)"
Dim strMessageErrorTitle As String = "Error"
Try
intNumberOfPeople = Convert.ToInt32(txtAmountOfPeople.Text)
If intNumberOfPeople > 0 And intNumberOfPeople < 100 Then
blnValidityCheck = True
Else
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
End If
Catch Exception As FormatException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
Catch Exception As OverflowException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
Catch Exception As SystemException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
End Try
Return blnValidityCheck
End Function
Private Function ValidateTicketIsSelected(ByRef blnTicket As Boolean, _
ByRef strTicket As String) As Integer
Dim intTicketChoice As Integer
Try
intTicketChoice = Convert.ToInt32(lstSeatingType.SelectedIndex)
strTicket = lstSeatingType.SelectedItem.ToString()
blnTicket = True
Catch Exception As SystemException
' Detects if a tour not selected
MsgBox("Select a Ticket Choice", , "Error")
blnTicket = False
End Try
Return intTicketChoice
End Function
Private Function SeasonTicketsFindCost(ByVal intTicketSelection As Integer, _
ByVal intGroupSize As Integer) As Decimal
Dim decTicketCost As Decimal
Dim decFinalCost As Decimal
Dim decBoxSeats As Decimal = 2500D
Dim decLowerdeck As Decimal = 1500D
Select Case intTicketSelection
Case 0
decTicketCost = decBoxSeats
Case 1
decTicketCost = decLowerdeck
End Select
decFinalCost = decTicketCost * intGroupSize
Return decFinalCost
End Function
Private Function SingleGameTicketsFindCost(ByVal intTicketSelection As Integer, _
ByVal intGroupSize As Integer) As Decimal
Dim decTicketCost As Decimal
Dim decFinalCost As Decimal
Dim decBoxSeats As Decimal = 55D
Dim decLowerDeck As Decimal = 35D
Dim decUpperDeck As Decimal = 25D
Dim decStandingRoomOnly As Decimal = 15D
Select Case intTicketSelection
Case 0
decTicketCost = decBoxSeats
Case 1
decTicketCost = decLowerDeck
Case 2
decTicketCost = decUpperDeck
Case 3
decTicketCost = decStandingRoomOnly
End Select
decFinalCost = decTicketCost * intGroupSize
Return decFinalCost
End Function
End Class