I have to write a program that calculates costs for a catering company. i have that part down, but whats stumping me is I have trouble displaying the total. What also is stumping me is that i have to make a summary button that adds everything up into a grand total from the previous calculations and display it in a message box. displaying and calculations aren't really my issues, but getting the data to calculate is.
Thank you
HERE's the code.
Const decPRIME_RIB As Decimal = 25.95D
Const decCHICKEN As Decimal = 18.95D
Const decPASTA As Decimal = 12.95D
Const decOPEN_BAR As Decimal = 25D
Const decWINE As Decimal = 8D
Const decBEER As Decimal = 10D
'Declare module-level variables for summary information.
Private TotalDollar As Decimal
Private AmountDue As Decimal
Private SubTotalDecimal As Decimal
Private TotalDecimal As Decimal
Private Guest As Integer
Private EventCountInteger As Integer
Private Sub CalcBtn_Click(sender As Object, e As EventArgs) Handles CalcBtn.Click
' Calculate and display the current amounts and add to totals.
Dim FoodChoiceDecimal As Decimal
Dim OpenBarDecimal As Decimal
Dim WineDecimal As Decimal
Dim DrinksDecimal As Decimal
' Find the price.
If PrimeRB.Checked Then
FoodChoiceDecimal = decPRIME_RIB
ElseIf ChickRB.Checked Then
FoodChoiceDecimal = decCHICKEN
ElseIf PastaRB.Checked Then
FoodChoiceDecimal = decPASTA
End If
If OpenCB.Checked Then
OpenBarDecimal = decOPEN_BAR
End If
If WineCB.Checked Then
WineDecimal = decWINE
End If
'Multiply price by number of guest and drink selection.
Try
DrinksDecimal = (OpenBarDecimal + WineDecimal)
AmountDue = (FoodChoiceDecimal + DrinksDecimal) * Guest
' display totals.
TotalLbl.Text = TotalLbl.ToString("C")
' Allow change for new event.
OpenCB.Enabled = False
WineCB.Enabled = False
ClearBtn.Enabled = True
SummaryBtn.Enabled = True
Catch NumberOfGuestsException As FormatException
MessageBox.Show("Number of Guests must be Numeric", _
"Data entry Error", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End Try
End Sub
Private Sub SummaryBtn_Click(sender As Object, e As EventArgs) Handles SummaryBtn.Click
' Calculate total dollar amounts and number of events.
Dim MessageString As String
If EventCountInteger > 0 Then
' Calculate the summary sales totals.
TotalDollar += AmountDue
'Concatenate the message string.
MessageString = "Number of Events:" & EventCountInteger.ToString() _
& Environment.NewLine & Environment.NewLine _
& "Total Sales: " & TotalDollar.ToString("C")
MessageBox.Show(MessageString, "Sales Summary", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
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'm currently taking a basic Microsoft Visual Studio 2017 course. The question asks me to import and read the contents from a text file to calculate and display the energy cost savings for a smart home. I am stuck starting on the comment, ' The formula for the average monthly savings inside the loop to repeat the process' on line 96 where I am supposed to calculate the average formula for the energy savings. I would also like to know how I can display the three labels. The name of the text formula is savings.txt. These are its contents:
January
38.17
February
41.55
March
27.02
April
25.91
May
3.28
June
18.08
July
45.66
August
16.17
September
3.98
October
17.11
November
25.78
December
51.03
Are there any additional changes I can make to improve my code? I am new to this course and welcome any suggestions or examples.
Here is also a link to my rubric. Please let me know if you cannot access its contents:
https://maricopa-my.sharepoint.com/:w:/g/personal/ric2084617_maricopa_edu/ETNr_-i-wllOr9zsRiNTyMIBG0CcNO1xICcaYVYmgKl7YA?e=tLq4Ng
I am certain I have the required variables declared. I am at a loss of how to apply them into the average formula. Should I add each of the costs from the text file or is there a more simple yet basic method to add them?
' Program Name: Smart Home Electric Savings
' Author: Richard Lew
' Date: October 27, 2019
' Purpose: This Windows application opens a text file that lists the monthly savings of a smart home's electric bill in comparison to a previous year
' without smart device activation. A smart thermostat, lighting system, and water heater were installed one year ago and the text file lists
' the savings each month. The The user selects a month read from the text file and displays that month's electric bill savings. A Button object
' displays the average monthly savings with the smart home devices and the month with the most significant savings.
Option Strict On
Public Class frmSavings
' Class Level Private variables
Private _intMonthsOfSmartSavings As Integer = 12
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strSavings(_intSizeOfArray) As String
Private _strSavingsMonth(_intSizeOfArray) As String
Private _decInitialBill(_intSizeOfArray) As Decimal
Private _intMonth(_intSizeOfArray) As Integer
Private Sub fromSavings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' The frmSavings load event reads the savings text file and fills the label objects with the savings.
' Initialize an instance of the StreamReader object and declare variables
Dim objReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "D:\CIS 159\VB_Student_Data_Files\Chapter 8\savings.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Restart when the file is available."
' Verify the file exists
If IO.File.Exists(strLocationAndNameOfFile) Then
objReader = IO.File.OpenText(strLocationAndNameOfFile)
' Read the file line by line until the file is completed
Do While objReader.Peek <> -1
_strSavings(intCount) = objReader.ReadLine()
_strSavingsMonth(intCount) = objReader.ReadLine()
_decInitialBill(intCount) = Convert.ToDecimal(objReader.ReadLine())
_intMonth(intCount) = Convert.ToInt32(objReader.ReadLine())
intCount += 1
Loop
objReader.Close()
' The Monthly Savings Combo Box object is filled with the months of the savings
For intFill = 0 To (_strSavingsMonth.Length - 1)
cboMonthSavings.Items.Add(_strSavingsMonth(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Close()
End If
End Sub
Private Sub BtnDisplayStatistics_Click(sender As Object, e As EventArgs) Handles btnDisplayStatistics.Click
' The btnDisplayStatistics click event calls the savings Sub procedures
' Declare variables
Dim intSelectedMonth As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectedMonthError As String = "Select a Month"
Dim strSelectedMonth As String = ""
Dim intMonthChoice As Integer
Dim blnMonthIsSelected As Boolean = False
' If the Month Savings Combo Box is selected, then display the statistics
If cboMonthSavings.SelectedIndex >= 0 Then
intSelectedMonth = cboMonthSavings.SelectedIndex
Else
MsgBox(strSelectedMonthError, , strMissingSelection)
End If
End Sub
Private Sub MonthSavingsComboBox(ByVal intMonth As Integer)
' This Sub procedure computes and displays the savings for the month selected
' Declare variables
Dim intDoublePresentMonth As Integer
Dim decDoubleAverage As Decimal = 0
Dim decDoublePresentMonthValue As Decimal = 0
Dim decDoubleSavings As Decimal
Dim decAverageSavings As Decimal
Dim decTotal As Decimal
Dim decDoubleTotal As Decimal = 0.0D
Dim strPresentSavingsMonth As String = ""
Dim strPresentSavingsMonthValue As String = ""
Dim decSavingsMonth As Decimal
Dim strMonthOfSavings As String = ""
Dim decAverageSavingsOfMonth As Decimal
Dim decSignificantSavingsOfMonth As Decimal
Dim strMonthOfSignificantSavings As String = ""
' The procedure MakeObjectsVisible is called to display the Form objects
MakeObjectsVisible()
'Display the values and quantity of the selected values
lblDisplayMonthSavings.Text = "The electric savings for " & strPresentSavingsMonth & " is " & _strSavings(intMonth)
lblDisplayAverageMonthlySavings.Text = "The average monthly savings: " & decAverageSavings.ToString("C0")
lblDisplayMonthMostSignificantSavings.Text = _decInitialBill(intMonth) & " had the most significant monthly savings"
' The loop repeats for the life of the values
For intDoublePresentMonth = 1 To _intMonthsOfSmartSavings
' The formula for the average monthly savings inside the loop to repeat the process
decAverageSavings = decDoubleTotal / _intMonthsOfSmartSavings
' Displays the savings amounts
cboMonthSavings.Items.Add(intDoublePresentMonth.ToString())
' Accumulates the total of the savings
decTotal += decDoubleSavings
Next
End Sub
Private Sub MakeObjectsVisible()
' This procedure displays the objects showing the results
lblDisplayMonthSavings.Visible = True
btnDisplayStatistics.Visible = True
lblDisplayAverageMonthlySavings.Visible = True
lblDisplayMonthMostSignificantSavings.Visible = True
' The previous data is removed
cboMonthSavings.Items.Clear()
lblDisplayMonthSavings.Text = ""
lblDisplayAverageMonthlySavings.Text = ""
lblDisplayMonthMostSignificantSavings.Text = ""
End Sub
Private Sub MnuFile_Click(sender As Object, e As EventArgs) Handles mnuFile.Click
' The mnuFile click event displays the mnuClear and and mnuExit buttons
End Sub
Private Sub MnuClear_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
' The mnuClear click event clears and resets the form
cboMonthSavings.Items.Clear()
lblDisplayMonthSavings.Text = ""
lblDisplayAverageMonthlySavings.Text = ""
lblDisplayMonthMostSignificantSavings.Text = ""
lblDisplayMonthSavings.Visible = False
lblDisplayAverageMonthlySavings.Visible = False
lblDisplayMonthMostSignificantSavings.Visible = False
End Sub
Private Sub MnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
' The mnuExit click event closes the application
Application.Exit()
End Sub
End Class
Im using visual basic language on visual studio 2010.I want to be asked to enter the cash payed after im done picking the order, now it asks to enter cash after every item i choose.
below you'll find the code and screenshots
Dim choice As String
Dim price As Double
Dim quantity As Integer
Dim total As Double
Dim tpayable As Double
Dim cash As Double
Dim change As Double
Dim spaces As String = Space(4)
Private Sub menue_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim spaces As String = Space(4)
End Sub
Private Sub badd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles badd.Click
quantity = InputBox("enter item quantity", "quantity")
If RadioButton1.Checked Then
choice = "Potato soup"
price = "80"
ElseIf RadioButton2.Checked Then
choice = "Salmon roll"
price = "100"
ElseIf RadioButton3.Checked Then
choice = "Smoked salmon potatos"
price = "75"
End If
If RadioButton4.Checked Then
choice = "Lasagna"
price = "250"
ElseIf RadioButton5.Checked Then
choice = "Cheese burger"
price = "120"
ElseIf RadioButton6.Checked Then
choice = "Pizza"
price = "450"
ElseIf RadioButton7.Checked Then
choice = "ugali & sukuma"
price = "80"
ElseIf RadioButton8.Checked Then
choice = "Chicken fried noodles"
price = "150"
End If
If RadioButton9.Checked Then
choice = "Chocolate fudge cake"
price = "250"
ElseIf RadioButton10.Checked Then
choice = "Ice cream"
price = "150"
ElseIf RadioButton11.Checked Then
choice = "Carrot Cake"
price = "230"
End If
If RadioButton12.Checked Then
choice = "Black tea"
price = "80"
ElseIf RadioButton13.Checked Then
choice = "White tea"
price = "80"
ElseIf RadioButton14.Checked Then
choice = "Coffee"
price = "80"
End If
If RadioButton15.Checked Then
choice = "Coke"
price = "60"
ElseIf RadioButton16.Checked Then
choice = "Milkshake"
price = "110"
ElseIf RadioButton17.Checked Then
choice = "Fanta"
price = "60"
End If
total = quantity * price
tpayable += total
txttpayable.Text = Str(tpayable)
cash = InputBox("enter cash payed")
txtcgiven.Text = Str(cash)
change = cash - tpayable
txtchange.Text = Str(change)
ListBox1.Items.Add(String.Concat(choice & spaces & price & spaces & quantity & spaces & total & spaces & tpayable))
End Sub
screenshot
The application can't read your mind. It can only react to some input from you. You need to handle an appropriate event to let the application know that you have made all the appropriate selections and so it needs to prompt. Looking more closely at your code, it appears that you have several groups of RadioButtons. Assuming that the user must select one option from each group, you can handle the CheckedChanged event of all the RadioButtons and then check whether one is checked from each group. Here's a simplified example using two groups of two that you can extend to any number of groups and controls:
Private Sub RadioButtons_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged,
RadioButton2.CheckedChanged,
RadioButton3.CheckedChanged,
RadioButton4.CheckedChanged
If Panel1.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) AndAlso
Panel2.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) Then
'A selection has been made from each group.
End If
End Sub
This assumes that RadioButton1 and RadioButton2 are on Panel1 and RadioButton2 and RadioButton3 are on Panel2. As I said, there can be as many groups as you like and each group can contain as many options as you like. Each group can be on a Panel, a GroupBox or some other container.
I have started over and everything is working as intended except for 2 of the accumulating totals, the calculation is not working the way I need it to. Instead of adding previous sales to the total it tacks the new sale on the end...
for example: I input 1 Snowboard and 1 Snowboard with Boots, this works, 1 is shown in the summary for both Snowboards and Snowboards with Boots. However when I try to input again in order to keep a running total of sales I have a problem, I enter 1 Snowboard and 1 Snowboard with Boots, and the summaries show 11 rather than 2. Why does this happen?
' Declare module-level variables and constants.
Private SnowBoardsSold, BootsSold, SaleCount As Integer
Private ItemsSold As Integer
Private TotalSales As Decimal
Const SNOWBOARD_RATE As Decimal = 20D
Const BOOTS_RATE As Decimal = 30D
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
' Calculate the prices
Dim SnowBoards, Boots As Integer
Dim SnowBoardSale, BootsSale, ThisSale, AverageSalesEver As Decimal
Try
' Convert the Snowboard input to numeric variable.
SnowBoards = Integer.Parse(SnowboardsTextBox.Text)
Try
' Convert Boots if Snowboard was successful.
Boots = Integer.Parse(WithBootsTextBox.Text)
' Calculate values for sale.
SnowBoardSale = SnowBoards * SNOWBOARD_RATE
BootsSale = Boots * BOOTS_RATE
ThisSale = SnowBoardSale + BootsSale
' Calculate summary values.
TotalSales += ThisSale
BootsSold += BootsSale
SnowBoardsSold += SnowBoardSale
SaleCount += 1
AverageSalesEver = TotalSales / SaleCount
' Format and display prices for the sale.
SnowBoardsPriceTextBox.Text = SnowBoardSale.ToString("c")
BootsPriceTextBox.Text = BootsSale.ToString("c")
TotalPriceTextBox.Text = ThisSale.ToString("c")
' Format and display values for the summary.
SnowBoardRentalTextBox.Text += SnowBoards.ToString()
BootsRentalTextBox.Text += Boots.ToString()
TotalChargesTextBox.Text = TotalSales.ToString("c")
AverageChargeTextBox.Text = AverageSalesEver.ToString("c")
Catch BootsException As FormatException
' Handle a Boots exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With WithBootsTextBox
.Focus()
.SelectAll()
End With
End Try
Catch SnowBoardsException As FormatException
' Handle a SnowBoard exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With SnowboardsTextBox
.Focus()
.SelectAll()
End With
Catch AnException As Exception
'Handle any other exception.
MessageBox.Show("Error: " & AnException.Message)
End Try
End Sub
First, you might want to change the way you grab the numbers:
'Convert snowboard input value to numeric variable.
SnowboardInteger = Integer.Parse(SnowboardsTextBox.Text)
to:
Dim SnowboardInteger As Integer
If TryParse.Integer(SnowboardsTextBox.Text, SnowboardInteger) = False then
' if it parses, SnowboardInteger will have the value,
'else the function returns false
MessageBox.Show("Please enter numbers")
End if
Also, you are parsing the textboxes twice. Once in the declaration then right after. This doesnt look right:
SnowboardSaleCountInteger += 1
WithBootsSaleCountInteger += 1
TotalSaleCountInteger += TotalChargesSumInteger ' ?????
AverageChargeInteger = TotalChargesSumInteger / TotalSaleCountInteger
Adding 'charges' to a 'counter' doesnt seem right. If you want the avg shouldnt it be:
TotalSaleCountInteger = SnowboardSaleCountInteger + WithBootsSaleCountInteger
If you want fractions such as 'xx.yy' in the result, AverageChargeInteger should be a Double or Decimal, unless whole dollars are ok for the assignment.
If you need to accumulate from previous clicks, then you need to move some declarations out of the procedure up by SnowboardSumInteger, WithBootsSumInteger so they can accumulate. As it is, WithBootsSaleCountInteger, TotalSaleCountInteger dont do anything and are always 1. I wonder if as a 'SaleCounter' they shouldnt increase by the value in the textbox rather than just 1 (dont have the assignment in front of me).
One more thing you might need to do is here:
SnowboardPriceInteger = SnowboardInteger * SNOWBOARD_RENTAL_RATE
WithBootsPriceInteger = WithBootsInteger * WITH_BOOTS_RENTAL_RATE
TotalPriceInteger = SnowboardPriceInteger + WithBootsPriceInteger
Your constants are Decimal (SNOWBOARD_RENTAL_RATE) so, the result of the calc has to go into a Decimal var, but SnowboardPriceInteger and the other are not. An integer cannot store a fractional result from the multiplication or division.
something like:
' sales accumulators
Private TotalSales As Decimal = 0
Private ItemsSold As Integer = 0
Click Event:
' this sale:
Dim Snowboards As Integer
Dim Boots As Integer
' get the values from the text boxes, then:
Dim SnowBoardSale As Decimal = (SnowBoards * SnowBoardRate)
Dim BootsSale As Decimal = (Boots * BootsRate)
Dim ThisSale As Decimal = SnowBoardSale + BootsSale
' update accumulators
TotalSales += ThisSale
ItemsSold += (Boots + Snowboards)
' calc the average
Dim AverageSalesEver AS Decimal = TotalSales / ItemsSold
' Display results in textboxes
'(this exercise is left to the student ;) )
HTH
I think you just confused yourself with too many variables and ones left over from old attempts.
Hey guys I have been having this crashing problem with my program.
I am trying to create a program where it calculates a persons account balance by inputting their beginning balance, credit limit, total charges, and total credits. In this case I am having specific problems with the Total Charges and Total Credits Code.
I have a message box set up to where if the Total Charges and total credits box are blank it will say "please enter a numeric value for ....". The problem is that when I do run it and enter a blank, the message shows up and then the program crashes.
After crashing, the The program then highlights in yellow the specific conversion code (in this case: decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)) and the error says Input string was not in correct format.
What's going on, I converted it into a correct format right? (decimal to decimal?). Here's an in depth look at my code:
Public Class frmEndingBalance
'Declare module level variables
Dim mdecEndingBalance As Decimal
Dim mdecAllCharges As Decimal
Dim mdecAllCredits As Decimal
Dim mintCustomersOverLimit As Integer
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'clears the form
'clears the labels
txtAccountNumber.Text = ""
txtBeginningBalance.Text = ""
txtTotalCharges.Text = ""
txtTotalCredits.Text = ""
txtCreditLimit.Text = ""
lblEndingBalance.Text = ""
lblCreditMessage.Text = ""
lblAllCharges.Text = ""
lblAllCredits.Text = ""
lblCustomersOverLimit.Text = ""
lblCreditMessage.Text = ""
'clear the textboxes
txtAccountNumber.Clear()
txtBeginningBalance.Clear()
txtTotalCredits.Clear()
txtTotalCharges.Clear()
txtCreditLimit.Clear()
'clear module level variables
mdecEndingBalance = 0
mdecAllCharges = 0
mdecAllCredits = 0
mintCustomersOverLimit = 0
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare Variables
Dim intAccountNumber As Integer
Dim intBeginningBalance As Integer
Dim decTotalCharges As Decimal
Dim decTotalCredits As Decimal
Dim decCreditLimit As Decimal
Dim mdecEndingBalance As Decimal 'Beginning Balance + Charges - Credits()
Dim decCreditMessage As Decimal
'check for numeric
If IsNumeric(txtAccountNumber.Text) = False Then 'value is not numeric
MessageBox.Show("You can't enter anything blank!")
Exit Sub
End If
'convert to a numeric data type
intAccountNumber = Convert.ToInt32(txtAccountNumber.Text)
'check for numeric
If String.IsNullOrEmpty(txtBeginningBalance.Text) Then MessageBox.Show("Beginning Balance Cannot Be Blank!")
'check for everything else
If IsNumeric(txtBeginningBalance.Text) = False Then 'Value is not numeric
MessageBox.Show("Please enter a numeric value for Beginning Balance!")
Exit Sub
End If
'convert to a numeric data type
intBeginningBalance = Convert.ToInt32(txtBeginningBalance.Text)
'check for numeric
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
'convert
decTotalCharges = Convert.ToDecimal(txtTotalCharges.Text)
'check for 0 or positive
If decTotalCharges < 0 Then
MessageBox.Show("Please enter a positive value or zero for number of Total Charges!")
Exit Sub
End If
'check for numeric
If IsNumeric(txtTotalCredits.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Credits")
End If
'convert to a numeric data type
decTotalCredits = Convert.ToDecimal(txtTotalCredits.Text)
'check for 0 or positive
If decTotalCredits < 0 Then
MessageBox.Show("Please enter a positive value or zero for total credits!")
End If
'check numeric
If IsNumeric(txtCreditLimit.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for the Credit Limit!")
End If
'convert to a numeric data type
decCreditLimit = Convert.ToDecimal(txtCreditLimit.Text)
'check for a 0 or positive
If decCreditLimit < 0 Then
MessageBox.Show("Please enter a positive value or zero for Credit Limit!")
End If
'check for customers over limit
decCreditMessage = decCreditLimit - (mdecEndingBalance)
'running totals
mdecAllCharges += decTotalCharges
mdecAllCredits += decTotalCredits
'calculate Ending Balance
mdecEndingBalance = Convert.ToDecimal(intBeginningBalance + decTotalCharges - (decTotalCredits))
'display outputs
lblEndingBalance.Text = mdecEndingBalance.ToString("c")
lblAllCharges.Text = mdecAllCharges.ToString("c")
lblAllCredits.Text = mdecAllCredits.ToString("c")
lblCustomersOverLimit.Text = mintCustomersOverLimit.ToString("n0")
End Class
Any Help would be greatly appreciated!
Thanks
You've missed Exit Sub out of the test
If IsNumeric(txtTotalCharges.Text) = False Then 'value is not numeric
MessageBox.Show("Please enter a numeric value for Total Charges!")
End If
You've done it in a few other places as well (as have we all , in fact as do we all :( ). Be worth refactoring with a little helper method or something similar.
If IsValidDecimal(txtTotalCharges.Text, "Total Charges")
' etc
End If