So I am writing this program that should return the total cost of a hospital stay. Everything appears to be working fine, except the most important part...the total cost of the hospital stay. I have looked everywhere for a possible solution, to no avail. The program continues to return $0.00 no matter what I do. No error messages, just $0.00 every single time. I realize I have not included exception handling as of yet, which I will do once I get the kinks worked out. Any idea what my issue is here? Thanks in advance!
Const decRatePerDay As Decimal = 350.0
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim NumOfDays As Integer
Dim MedCharges As Decimal
Dim SurgicalCharges As Decimal
Dim LabFees As Decimal
Dim RehabCharges As Decimal
Dim TotalCharges As Decimal
NumOfDays = CDec(txtNumOfDays.Text)
MedCharges = CDec(txtMedCharges.Text)
SurgicalCharges = CDec(txtSurgicalCharges.Text)
LabFees = CDec(txtLabFees.Text)
RehabCharges = CDec(txtLabFees.Text)
lblCalTotalCost.Text = TotalCharges.ToString("c")
End Sub
Function CalcStayCharges(NumOfDays As Integer) As Decimal
Dim decCostOfStay As Decimal
NumOfDays = CDec(txtNumOfDays.ToString)
decCostOfStay = NumOfDays * decRatePerDay
Return decCostOfStay
End Function
Function CalcMiscCharges(MedCharges As Decimal, SurgicalCharges As Decimal, LabFees As Decimal, RehabCharges As Decimal) As Decimal
Dim TotalMisc As Decimal
MedCharges = CDec(txtMedCharges.ToString)
SurgicalCharges = CDec(txtSurgicalCharges.ToString)
LabFees = CDec(txtLabFees.ToString)
RehabCharges = CDec(txtLabFees.ToString)
TotalMisc = MedCharges + SurgicalCharges + LabFees + RehabCharges
Return TotalMisc
End Function
Function CalcTotalCharges(CostOfStay As Decimal, TotalMisc As Decimal) As Decimal
Dim TotalCharges As Decimal
TotalCharges = CostOfStay + TotalMisc
lblCalTotalCost.Text = TotalCharges.ToString("c")
Return TotalCharges
End Function
You never set the value of TotalCharges and you never call your functions to calculate the total charges.
Change
lblCalTotalCost.Text = TotalCharges.ToString("c")
To
lblCalTotalCost.Text = CalcTotalCharges(CalcStayCharges(NumOfDays), _
CalcMiscCharges(MedCharges, SurgicalCharges, LabFees, RehabCharges)) _
.ToString("C")
Related
Just for context;
I need to calculate the average of 5 numbers located in 5 textboxes.
Nummer means number
Gemiddelde means average
and
Bereken means calculate
What is causing it to crash?
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
'Variabelen'
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + " Dit is onvoldoende"
End If
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or
nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
End Sub
I don't see what would crash the program but check to that the TextBoxes have values before assigning them to numeric variables. A Decimal value will never = "".
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click 'Variabelen'
If Not IsNumeric(txtNummer1.Text) Or _
Not IsNumeric(txtNummer2.Text) Or _
Not IsNumeric(txtNummer3.Text) Or _
Not IsNumeric(txtNummer4.Text) Or _
Not IsNumeric(txtNummer5.Text) Then
MessageBox.Show ("your mom wants you to fill in all the number boxes")
Exit Sub
End If
Dim nummer1 As Decimal = CDec(txtNummer1.Text)
Dim nummer2 As Decimal = CDec(txtNummer2.Text)
Dim nummer3 As Decimal = CDec(txtNummer3.Text)
Dim nummer4 As Decimal = CDec(txtNummer4.Text)
Dim nummer5 As Decimal = CDec(txtNummer5.Text)
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + "Dit is onvoldoende"
End If
If nummer1 = 0 Or nummer2 = 0 Or nummer3 = 0 Or nummer4 = 0 Or nummer5 = 0 Then
butBereken.Enabled = False
MessageBox.Show ("your mom")
Else
butBereken.Enabled = True
End If
End Sub
If this doesn't work I would consider setting breakpoints in the could to determine what line is causing the crash.
If that doesn't work consider adding this line to the form's initialization:
butBereken.Caption = "Warning: Do not Click!"
Assuming the user populated all the textboxes with numeric only data, (and you have checked this) try replacing these lines in your code with this code
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As Decimal = somNummers / 5
lblGemiddelde.Text = Gemiddelde.ToString("##0.0")
I'd do something more like:
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Dim values() As Decimal
Try
values = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim Gemiddelde As String = values.Average()
lblGemiddelde.Text = Gemiddelde & If(Gemiddelde < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
MessageBox.Show("your mom")
End Try
End Sub
I prefer this approach as it doesn't require repetitive lines of code, manually converting each TextBox to a Decimal. Since the TextBoxes are in an Array, we could also add another TextBox to the form and then add that name to the end of the Array. The rest of the code would not need to change at all; it would still just work as is.
From the Array of TextBox, we use a LINQ statement to extract the Text from each TextBox and add it to an Array of String called "inputs". From there, we convert every single String to a Decimal using Array.ConvertAll(), again avoiding repetitive code. If any of the input values is not a valid Decimal then an Exception will be thrown and we'll jump the the Catch block where the not so well written error message is displayed.
If there are no exceptions, then all String inputs were successfully converted to Decimals and stored in the "values" Array. Next we simply use the LINQ function Average() to get the average of all the values.
Lastly we display the computed average in the Label, adding the "Dit is onvoldoende" message if approapriate. The If() function used in this line is simply a shorthand version of a longer If...Else...End If statement.
In your original attempt, it looks like you wanted to disable the button if any of the values are blank (or maybe if they are invalid decimals?):
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
This makes no sense as if you disable the button, how would it get turned back on so that user could click it again?
A different approach would be to handle the TextChanged() event of all the TextBoxes and simply update your Label with the average in real-time whenever one of the TextBoxes is changed:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateAverage()
End Sub
Private Sub txtAll_TextChanged(sender As Object, e As EventArgs) Handles txtNummer5.TextChanged, txtNummer4.TextChanged, txtNummer3.TextChanged, txtNummer2.TextChanged, txtNummer1.TextChanged
UpdateAverage()
End Sub
Private Sub UpdateAverage()
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Try
Dim values() As Decimal = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim average As Decimal = values.Average
lblGemiddelde.Text = average & If(average < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
lblGemiddelde.Text = "{ Invalid Input }"
End Try
End Sub
End Class
Sample run:
I need to make a phone bill program that would allow the user to calculate their phone bill. They would enter their minutes, texts and data allowance as well as how much they've used.
Each extra minute is 30p, each extra text is 10p and data used over the limit is £10.00, all added to the final cost.
The problem is that I cannot get the program to calculate the cost of each minute, I guess that after finding out how the minutes are calculated I will be able to do the same for the texts and the data.
Thanks for the help, much appreciated.
This is the problem
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btn1TotalCost_Click(sender As Object, e As EventArgs) Handles btn1TotalCost.Click
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim TextsAllowed As Integer
Dim TextsUsed As Integer
Dim DataAllowed As Integer
Dim DataUsed As Integer
Dim MinutesTotalCost As Double
Dim TextsTotalCost As Double
Dim DataTotalCost As Double
Dim MonthlyCost As Double
Dim TotalCost As Double
MinutesAllowed = Val(txtBoxMinutesAllowed.Text)
MinutesUsed = Val(txtBoxMinutesUsed.Text)
TextsAllowed = Val(txtBoxTextsAllowed.Text)
TextsUsed = Val(txtBoxTextsUsed.Text)
DataAllowed = Val(txtBoxDataAllowed.Text)
DataUsed = Val(txtBoxDataUsed.Text)
MinutesTotalCost = Val(txtBoxTotalCost.Text)
TextsTotalCost = Val(txtBoxTotalCost.Text)
DataTotalCost = Val(txtBoxTotalCost.Text)
TotalCost = Val(txtBoxTotalCost.Text)
'Minutes
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
'Texts
TextsAllowed = Integer.Parse(txtBoxTextsAllowed.Text)
TextsUsed = Integer.Parse(txtBoxTextsUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If TextsAllowed >= TextsUsed Then
TextsTotalCost = 0
Else
TextsTotalCost = (TextsUsed - TextsAllowed) * 0.15
End If
txtBoxTotalCost.Text = CType(TextsTotalCost + MonthlyCost, String)
'Data
DataAllowed = Integer.Parse(txtBoxDataAllowed.Text)
DataUsed = Integer.Parse(txtBoxDataUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If DataAllowed >= DataUsed Then
DataTotalCost = 0
Else
DataTotalCost = (DataUsed - DataAllowed) + 10.0
End If
txtBoxTotalCost.Text = CType(DataTotalCost + MonthlyCost, String)
End Sub
End Class
MinutesTotalCost = MinutesUsed - MinutesAllowed * 0.3
Multiplication and division operators have precedence over the addition and subtraction operators.
You need to add brackets to the calculation.
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
You also overwrite the result of the calculation here:
MinutesTotalCost = txtBoxTotalCost.Text
Edit: Working code for just the minutes
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim MinutesTotalCost As Double
Dim MonthlyCost As Double
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
Val() returns a double so you need to use Integer.Parse() for int.
Double needs to be converted to string for the textbox.
Edit 2:
Since MonthlyCostdoesn't change you need the line
MonthlyCost = Val(txtBoxMonthlyCost.Text)
only once at the beginning.
You are always overwriting the value of txtBoxTotalCost. Just make a single calculation with all costs i.e.
txtBoxTotalCost.Text = CType(MinutesTotalCost + TextsTotalCost + DataTotalCost + MonthlyCost, String)
I need some help creating a mortgage loan calculator that allows the user to input the loan amount, loan years and loan rate and calculates the monthly mortgage payment and displays the amounts due for each month in a datagridview control. The problem is , i cannot seem to loop it using a for loop, i need to use the loop to display all the monthly payments but with my attempt it just repeats the same amounts for every month.Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim loanAmount As Double
Dim loanYears As Integer
Dim loanRate As Double
Dim monthlyPayment As Double
Dim numberofPayments As Integer
Dim monthlyInterest As Double
Dim decimalInterest As Double
Dim interestPaid As Double
Dim newBalance As Double
Dim principle As Double
Dim n As Integer
Dim Pmt As Integer = 1
loanAmount = Val(TextBox1.Text)
loanYears = Val(TextBox2.Text)
loanRate = Val(TextBox3.Text)
decimalInterest = loanRate / 100
numberofPayments = loanYears * 12
monthlyInterest = decimalInterest / 12
Label1.Text = monthlyPayment
For Pmt = 1 To numberofPayments
n = n + 1
If n = numberofPayments + 1 Then
Exit For
End If
monthlyPayment = loanAmount * monthlyInterest / (1 - (1 + monthlyInterest) ^ -numberofPayments)
interestPaid = loanAmount * monthlyInterest
principle = monthlyPayment - interestPaid
newBalance = loanAmount - principle
Me.DataGridView1.Rows.Add(n, Math.Round(monthlyPayment, 2), Math.Round(interestPaid, 2), Math.Round(principle, 2), Math.Round(newBalance, 2))
Next
End Sub
If someone could please help me out , it would be much appreciated.
Thank you
You need loanAmount = loanAmount - principle inside the For, or some other statement that tracks the principle balance and uses it in each iteration. It looks like you're trying to do that with the newBalance variable, but each iteration status over with loanAmount, which never decreases, so the values never change. I would suggest tracing through your math and making sure that your algorithm is actually performing the operations you desire.
So I have this program. It calculates the sale price of an item and displays the tax, subtotal, discount percent, which all works fine. The thing im trying to do is show 3 more textbox that accumulate the subtotal, discount amount, and the average discount.
Everytime I type anything in, the textboxs that are supposed to be accumulating are just displaying what the other boxs say, basically duplicating the boxs
Dim numberOfInvoices As Integer
Dim totalOfInvoices As Decimal
Dim invoiceAverage As Decimal
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim subtotal As Decimal = CDec(txtEnterSubtotal.Text)
Dim discountPercent As Decimal = 0.25D
Dim discountAmount As Decimal = Math.Round(subtotal * discountPercent, 2)
Dim invoiceTotal As Decimal = subtotal - discountAmount
Dim enterSubtotal As Decimal = Val(txtEnterSubtotal.Text)
Dim accumDiscount As Decimal = Val(txtAccumDiscAmount.Text)
Dim avgDiscount As Decimal = Val(txtAccumDiscAmount.Text)
Dim accumSubTotal As Decimal = Val(txtAccumSubtotal.Text)
txtSubtotal.Text = FormatCurrency(subtotal)
txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
txtDiscountAmount.Text = FormatCurrency(discountAmount)
txtTotal.Text = FormatCurrency(invoiceTotal)
numberOfInvoices += 1
totalOfInvoices += invoiceTotal
invoiceAverage = totalOfInvoices / numberOfInvoices
txtNumberOfInvoices.Text = numberOfInvoices.ToString
txtTotalOfInvoices.Text = FormatCurrency(totalOfInvoices)
txtInvoiceAverage.Text = FormatCurrency(invoiceAverage)
'below is where I'm trying to accumulate everything entered....
txtAccumSubtotal.Text = FormatCurrency(accumSubTotal + subtotal)
txtAccumDiscAmount.Text = FormatCurrency(accumDiscount + discountAmount)
If avgDiscount = 0 Then
txtAvgDiscAmount.Text = FormatCurrency(discountAmount)
ElseIf avgDiscount > 0 Then
txtAvgDiscAmount.Text = FormatCurrency(avgDiscount / numberOfInvoices)
End If
txtEnterSubtotal.Text = ""
txtEnterSubtotal.Select()
'This is a comment
End Sub
Ignore my previous post, I was wrong. I found the problem.
VAL() on a percent or currency field will return 0. You have to take the "$" and "%" out of your string to do a VAL().
i have a sub that will try to get random foods in the database, get the sum of these food's calories and check if they wont exceed the required calories.
most of the time the sub worked, but sometimes this error appears.
this is my code. it is kinda long.
Private Sub lunchgenerate()
Dim grams As Integer = DSgrams.Tables("grams").Rows(0).Item("grams")
Dim grams1 As Integer = DSricegrams.Tables("ricegrams").Rows(0).Item("grams")
Dim grams2 As Integer = DSgrams2.Tables("grams").Rows(0).Item("grams")
Dim calorieval As Decimal = foodcalories * grams
Dim calorieval1 As Decimal = ricecalories * grams1
Dim calorieval2 As Decimal = foodcalories2 * grams2
Dim carbval As Decimal = foodcarb * grams
Dim carbval1 As Decimal = ricecarb * grams1
Dim carbval2 As Decimal = foodcarb2 * grams2
Dim proteinval As Decimal = foodprotein * grams
Dim proteinval1 As Decimal = riceprotein * grams1
Dim proteinval2 As Decimal = foodprotein2 * grams
Dim fatval As Decimal = foodfat * grams
Dim fatval1 As Decimal = ricefat * grams1
Dim fatval2 As Decimal = foodfat2 * grams
Dim caloriepercent As Decimal = usercalories * 0.5
Dim mincalories As Decimal = caloriepercent - 300
Dim proteinpercernt As Decimal = userprotein * 0.5
Dim minprotein As Decimal = proteinpercernt - 20
Dim counter As Integer = 0
Dim counter1 As Integer = 0
Dim foodcalorietotal As Decimal = calorieval + calorieval1 + calorieval2
Dim foodproteintotal As Decimal = proteinval + proteinval1 + proteinval2
Dim carbtotal As Decimal = carbval + carbval1 + carbval2
Dim foodfattotal As Decimal = fatval + fatval1 + fatval2
If foodcalorietotal < mincalories Or foodcalorietotal > caloriepercent Then
counter = 0
Else
counter = 1
End If
If foodproteintotal < minprotein Or foodproteintotal > proteinpercernt Then
counter1 = 0
Else
counter1 = 1
End If
If counter = 1 And counter1 = 1 Then
'output to the form
Else
**lunchgenerate()**
End If
End If
End Sub
i think the error is when the lunchgenerate() sub is called again.
but just like what i said, most of the times it worked, but sometimes it freezes and then this error appears and then highlights the first line of my code which is
Dim DAlunchcategory As New SqlDataAdapter(lunchquery, CN)
Dim DSlunchcategory As New DataSet
DAlunchcategory.Fill(DSlunchcategory, "category_id")
Stack Overflow error happens when there is no space on the stack (part of the process memory used for local variables, parameter values, function results and a few other little things).
Often the code that produces this error does it by executing infinite recursion. If the code that you showed is complete lunchgenerate function, in the case when either counter or counter1 is not 1, lunchgenerate will be called again with exactly the same outcome, and again, and again, until it completely depletes space on the stack and exception is thrown. You need to have some escape logic to avoid it.