Why is skipping the else part of my code? - vb.net

'REQUIREMENTS:Write a Visual Basic procedure called CalculateTotalCost that reads user-entered data from the txtQuantity and txtUnitCost TextBox controls. The CalculateTotalCost procedure should convert the text entered in the two TextBox controls into numbers. It should then multiple the two numbers together, apply the appropriate discount based on the quantity ordered, and display the result in the lblTotalCost Label control.
The following error-checking rules apply:
a. The text entered by the user in the txtQuantity TextBox control must represent a non-negative Integer. If it does not, the procedure should output the phrase “Invalid quantity!” in the lblTotalCost Label control and no further processing should take place.
b. The text entered by the user in the txtUnitCost TextBox control must represent a non-negative Double. If it does not, the procedure should output the phrase “Invalid unit cost!” in the lblTotalCost Label control and no further processing should take place.
Assuming no user input errors, the properly discounted total presented in the lblTotalCost Label control should be displayed in currently format. The display should contain a leading currency symbol (depending on how the computer was set up, this will probably be a dollar sign) and exactly two trailing digits after the included decimal point.
Public Class Form1
Private Sub lblTotalCost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblTotalCost.Click
'Author: Eric Konga_ 14200694 _BCIT/3_ The Papaua New Guinea University of Technology
' this program will read read user entered data from the two text boxes on the form and
' will calcualte (Multiply) the two numbers together and will then apply the appropriate discount
'based on the quantity ordered, and display the result(Total Cost) in the Label control.
'Declaring Variables as strings. This sets will out put to the screen the appropriate percentages
'based the quantity ordered.
Dim strDiscount As String
Dim strDiscount1 As String
Dim strDiscount2 As String
Dim strDiscount3 As String
Dim strDiscount4 As String
'declaring variables as integer, double and long. this sets of program will output to the screen
'
Dim intQuantity As Integer
Dim dblUnitCost As Double
Dim dblTotalCost As Double
'Assigning Variables
strDiscount = "0%"
strDiscount1 = "20%"
strDiscount2 = "30%"
strDiscount3 = "40%"
strDiscount4 = "50%"
' This is a mathematical calculator that calculates the TotalCost (TC).
intQuantity = txtQuantity.Text
dblUnitCost = txtUnitCost.Text
dblTotalCost = intQuantity * dblUnitCost
If intQuantity <= 9 Then
lblTotalCost.Text = "The Total Cost is: $" & String.Format("{0:n2}", dblTotalCost) & " and it's " & strDiscount & _
" Discount."
ElseIf intQuantity <= 19 Then
lblTotalCost.Text = "The Total Cost is: $" & String.Format("{0:n2}", dblTotalCost) & " and it's " & strDiscount1 & _
" Discount."
ElseIf intQuantity <= 49 Then
lblTotalCost.Text = "The Total Cost is: $" & String.Format("{0:n2}", dblTotalCost) & " and it's " & strDiscount2 & _
" Discount."
ElseIf intQuantity <= 99 Then
lblTotalCost.Text = "The Total Cost is: $" & String.Format("{0:n2}", dblTotalCost) & " and it's " & strDiscount3 & _
" Discount."
ElseIf intQuantity >= 100 Then
lblTotalCost.Text = "The Total Cost is: $" & String.Format("{0:n2}", dblTotalCost) & " and it's " & strDiscount4 & _
" Discount."
' under this condition, it will only execute if the integer(QTY) is negative or
'the unser entered float(UC) is negative.
Else
lblTotalCost.Text = (" Invalid Quantity!" & " or Ivalid Unit Cost!")
End If
End Sub
End Class

Because your first if condition is <= 9. This includes all negative integers.

Related

Why is my if statement only returning the second result?

My calculations work but every time I run the program my output will be the "negative, does not exceed" result. I'm very new to all this so please any suggestions will help.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim foodname As String = MaskedTextBox1.Text
Dim calories As Integer = MaskedTextBox2.Text
Dim fat As Integer = MaskedTextBox3.Text
Dim calculation As Double = (fat * 9) / calories
Dim positive As String = "which exceeds AHA recommendation"
Dim negative As String = "which does not exceed AHA recommendation"
ListBox1.Items.Clear()
If ((fat * 9) / calories) > (0.3 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & positive)
ElseIf ((fat * 9) / calories) < (0.29 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & negative)
End If
End Sub
End Class
would this help?
If ((fat * 9) / calories) > (0.3 * 100) Then
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & positive)
Else
ListBox1.Items.Add(foodname & " contains " & FormatPercent(calculation) & " calories from fat, " & negative)
End If
you have only two options here, no need for 2 conditions. either the first one is true, or it must be the second one

How do I display the years correctly in my vb.net coding?

I'm a beginner at using visual basic and I'm having trouble displaying my years correctly in my application. My application should display Rates: 3% - 7%, then under each rate Years should display: 1-5 and Balance should display a total amount per year. What I'm getting is 3% rate, years 1-5, and balance for each year. 4% rate is getting year 6, instead of 1-5 and balance for year six. 5% Rate is displaying year 7 and balance for that year, and so on.
FYI: I need to keep the For...Next statement and incorporate a Do...Loop statement for "Years."
I inserted pics for a better understanding of what I'm trying to explain. I'd appreciate any help.
Correct Way Incorrect Way
Here is the code:
Dim dblDeposit As Double
Dim dblBalance As Double
Dim intYear As Integer = 1
Double.TryParse(txtDeposit.Text, dblDeposit)
txtBalance.Text = "Rate" & ControlChars.Tab &
"Year" & ControlChars.Tab & "Balance" &
ControlChars.NewLine
' Calculate and display account balances.
For dblRate As Double = 0.03 To 0.07 Step 0.01
txtBalance.Text = txtBalance.Text &
dblRate.ToString("P0") & ControlChars.NewLine
Do
dblBalance = dblDeposit * (1 + dblRate) ^ intYear
txtBalance.Text = txtBalance.Text &
ControlChars.Tab & intYear.ToString &
ControlChars.Tab & dblBalance.ToString("C2") &
ControlChars.NewLine
intYear = intYear + 1
Loop While intYear < 6
Next dblRate
You need to reset intYear before each iteration of the Do loop.
Dim dblDeposit As Double
Dim dblBalance As Double
Dim intYear As Integer = 1
Double.TryParse(txtDeposit.Text, dblDeposit)
txtBalance.Text = "Rate" & ControlChars.Tab &
"Year" & ControlChars.Tab & "Balance" &
ControlChars.NewLine
' Calculate and display account balances.
For dblRate As Double = 0.03 To 0.07 Step 0.01
txtBalance.Text = txtBalance.Text &
dblRate.ToString("P0") & ControlChars.NewLine
intYear = 1 ' Reset intYear here before each loop
Do
dblBalance = dblDeposit * (1 + dblRate) ^ intYear
txtBalance.Text = txtBalance.Text &
ControlChars.Tab & intYear.ToString &
ControlChars.Tab & dblBalance.ToString("C2") &
ControlChars.NewLine
intYear = intYear + 1
Loop While intYear < 6
Next dblRate
Some other recommendations:
String concatenation in a loop is inefficient because of how String works in .NET (String is immutable, so every operation that changes a string causes a reallocation and a copy, this is a somewhat expensive operation), so I recommend you use a StringBuilder and only assign txtBalance.Text at the very end.
You need to abort if the user enters invalid input. Also use the built-in currency parser (NumberStyles.Currency)
Always use Decimal or integer pennies/cents when working with money. Never use IEEE-754 floating-point types (Single and Double) to represent money because they are imprecise.
Avoid using Hungarian Notation (prefixing variable names with an abbreviation of their type).
Dim depositAmount As Decimal
If Not Decimal.TryParse( txtDeposit.Text, NumberStyles.Currency, CultureInfo.CurrentCulture, depositAmount ) Then
MsgBox( "Invalid input" ).
Exit Sub
End If
Dim sb As New StringBuilder()
sb.Append( "Rate Year Balance" ).AppendLine() ' Tab characters are embedded in the string literal.
' Calculate and display account balances.
For rate As Double = 0.03 To 0.07 Step 0.01
sb.AppendFormat( " {0:P0}", rate ).AppendLine();
Dim year As Integer = 1 ' Reset intYear here before each loop
Do
Dim balance As Decimal = depositAmount * ( 1 + rate ) ^ year ' I think you should add extra parenthesis to make it clear which value the `^ year` is being applied to.
sb.AppendFormat( " {0:D} {1:C2}", year, balance ).ToString()
year = year + 1
Loop While year < 6
Next rate
txtBalance.Text = sb.ToString()

Using and updating textfiles as data storage

I am not too sure why, but the current stock for all the items now appears as zero when it shows up in a listbox/on the 'receipt'. Also, I am struggling to get it to update back up from zero when it becomes zero.
Public Class Form1
Dim GTIN As String
Dim LineContaining As String
Dim quantity As String
Dim description As String
Dim singleamount As String
Dim singleprice As Double
Dim totalprices As Double
Dim correctcode As Boolean
Dim stocklevel As String
Dim requiredstock As Integer
Dim remainingstock As Integer
Dim stock As Integer
'declare variables
Private Sub btnEnterGTIN_Click(sender As Object, e As EventArgs) Handles btnEnterGTIN.Click
GTIN = getValidGTIN()
Call itemfinder(GTIN)
End Sub
Function getValidGTIN()
Dim GTIN, ValidGTINAmountCharacters As String
Dim GTINOK As Boolean
'Declaring variables.
GTINOK = False
Do
GTIN = InputBox("Enter the full GTIN Number (it should be 8 digits long)")
'Prompts the user to enter the GTIN.
ValidGTINAmountCharacters = Len(GTIN)
'Makes it so that the amount of characters of the GTIN is stored in the variable ValidGTINAmountCharacters.
If ValidGTINAmountCharacters = 8 Then GTINOK = True
'Makes it so the program will only accept an input if it was 8 characters long.
If Not IsNumeric(GTIN) Then GTINOK = False
'Makes it so that if any other character typed in apart from a number is not valid.
If Not GTINOK Then MsgBox("The GTIN Number isn't valid. It should be a 8 digit number. (Should not contain letters or symbols).")
'Makes it so that if the GTIN is not valid according to the above, a message appears saying it is invalid.
Loop Until GTINOK
Return GTIN
End Function
Private Sub itemfinder(ByVal GTIN As String)
Using reader As New IO.StreamReader("receipt_orders.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(GTIN) Then
LineContaining = line
Exit While
End If
End While
End Using
'reads the textfile to find the entered GTIN
description = Mid$(LineContaining, 10, 17)
singleamount = Mid$(LineContaining, 38, 4)
stocklevel = Mid$(LineContaining, 43, 2)
quantity = InputBox("Enter the quantity you require?")
'prompts user to input the quantity
Dim QuantityOK As Boolean
QuantityOK = False
If quantity <= stocklevel Then
QuantityOK = True
End If
Dim GTINOK As Boolean
GTINOK = False
Using reader As New IO.StreamReader("receipt_orders.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(GTIN) Then
GTINOK = True
Exit While
End If
End While
End Using
stocklevel = stock
If QuantityOK = False And stock > 0 Then
MsgBox("There is not enough of this item in stock, restocking item to extra stock needed. You will not get " _
& quantity & " items, but we can give you " & stocklevel & " and restock the remaining amount.")
requiredstock = quantity - stocklevel
totalprices = stocklevel * singleamount
lstGTIN.Items.Add(GTIN)
lstName.Items.Add(description)
lstQuantity.Items.Add(quantity)
lstInStock.Items.Add(stocklevel)
lstAdditionalStock.Items.Add(requiredstock)
lstSinglePrice.Items.Add(FormatCurrency(singleamount))
lstTotal.Items.Add(FormatCurrency(totalprices))
lstTotals.Items.Add(totalprices)
lstReceipt.Items.Add("GTIN Code: " & GTIN)
lstReceipt.Items.Add("Item: " & description)
lstReceipt.Items.Add("Quantity wanted: " & quantity)
lstReceipt.Items.Add("Quantity available: " & stocklevel)
lstReceipt.Items.Add("Required restock amount: " & requiredstock)
lstReceipt.Items.Add("Price per unit: " & FormatCurrency(singleamount))
lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
End If
If QuantityOK = False And stock = 0 Then
MsgBox("This item is out of stock. We will register this item for restock in time for your next purchase.")
requiredstock = quantity
totalprices = 0
lstGTIN.Items.Add(GTIN)
description = Mid$(LineContaining, 10, 17)
lstName.Items.Add(description)
lstQuantity.Items.Add(quantity)
lstInStock.Items.Add(stocklevel)
lstAdditionalStock.Items.Add(requiredstock)
lstSinglePrice.Items.Add(FormatCurrency(0))
lstTotal.Items.Add(FormatCurrency(totalprices))
lstTotals.Items.Add(totalprices)
lstReceipt.Items.Add("GTIN Code: " & GTIN)
lstReceipt.Items.Add("Item: " & description)
lstReceipt.Items.Add("Quantity wanted: " & quantity)
lstReceipt.Items.Add("Quantity available: " & stocklevel)
lstReceipt.Items.Add("Required restock amount: " & requiredstock)
lstReceipt.Items.Add("Price per unit: " & FormatCurrency(0))
lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
End If
'if the GTIN is found in the textfile it is valid.
'if the GTIN code was incorrect then put the listboxes as product not found or zero.
If QuantityOK = True Then
MsgBox("No restock of item needed.")
totalprices = quantity * singleamount
remainingstock = stocklevel - quantity
lstGTIN.Items.Add(GTIN)
lstName.Items.Add(description)
lstQuantity.Items.Add(quantity)
lstInStock.Items.Add(stocklevel)
lstAdditionalStock.Items.Add(requiredstock)
lstSinglePrice.Items.Add(FormatCurrency(singleamount))
lstTotal.Items.Add(FormatCurrency(totalprices))
lstTotals.Items.Add(totalprices)
'if the GTIN code was correct, calculate the subtotal amount and put information in listboxes.
lstReceipt.Items.Add("GTIN Code: " & GTIN)
lstReceipt.Items.Add("Item: " & description)
lstReceipt.Items.Add("Quantity: " & quantity)
lstReceipt.Items.Add("Quantity in stock: " & stocklevel)
lstReceipt.Items.Add("Required restock amount: " & requiredstock)
lstReceipt.Items.Add("Price per unit: " & FormatCurrency(singleamount))
lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
'adds all the information onto a receipt - updates after every purchase.
Dim contents As String = IO.File.ReadAllText("receipt_orders.txt")
If GTINOK = False Then
lstReceipt.Items.Add("GTIN Code: " & GTIN)
lstReceipt.Items.Add("Item: Product not found")
lstGTIN.Items.Add(GTIN)
lstName.Items.Add("Product not found!")
lstQuantity.Items.Add(0)
lstSinglePrice.Items.Add(FormatCurrency(0))
lstInStock.Items.Add(0)
lstAdditionalStock.Items.Add(0)
lstTotal.Items.Add(FormatCurrency(0))
lstTotals.Items.Add(0)
End If
contents = contents.Replace(stocklevel, remainingstock)
IO.File.WriteAllText("items_to_restock", contents)
End If
Dim totalprice As Double
For x As Integer = 0 To lstTotals.Items.Count - 1
totalprice += Val(lstTotals.Items.Item(x).ToString)
Next
'adds up the numbers in the total list box and puts in the text box TotalPrice.
txtTotalPrice.Text = FormatCurrency(totalprice.ToString)
'formats the total as a currency.
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'clears all listboxes
lstGTIN.Items.Clear()
lstName.Items.Clear()
lstQuantity.Items.Clear()
lstSinglePrice.Items.Clear()
lstTotal.Items.Clear()
lstTotals.Items.Clear()
lstReceipt.Items.Clear()
lstInStock.Items.Clear()
lstAdditionalStock.Items.Clear()
'clears the total text box
txtTotalPrice.Text = ""
End Sub
Private Sub btnShowCodes_Click(sender As Object, e As EventArgs) Handles btnShowCodes.Click
Process.Start("receipt_orders.txt")
End Sub
End Class

VB Payroll Calculator ( For..Next Loop help please?)

I am trying to figure out why my For...Next loop will not execute properly in this program. It was supposed to allow the user to input payroll information for 4 different employees; however, it just copies the user input for the first employee 4 times in the listbox. I entered the code as I understand it from http://msdn.microsoft.com/en-us/library/zxkf5z4b%28v=vs.71%29.aspx so I am not sure what I am doing wrong. I've tried changing the loop counter from 0 to 1 but that did not resolve the error.
Public Class Payroll
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close() 'Exit application.
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtHoursWorked.Clear()
txtHourlyPayRate.Clear()
txtStateTaxRate.Clear() ' Clear textboxes and set focus to txtHoursWorked.
txtFedTaxRate.Clear()
txtFICA.Clear()
txtHoursWorked.Focus()
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intCount As Integer = 0 ' Loop Counter.
Dim intGrossPay As Integer ' To hold gross pay.
Dim intStateTax As Integer ' To hold state tax withholding.
Dim intFedTax As Integer ' To hold fed tax withholding.
Dim intFICA As Integer ' To hold FICA withholding.
Dim intNetPay As Integer ' To hold net pay.
Dim strPay As String ' To hold output.
For intCount = 1 To 4 Step 1
'Calculate gross pay.
intGrossPay = txtHourlyPayRate.Text * txtHoursWorked.Text
'Calculate state income tax withholding.
intStateTax = intGrossPay * txtStateTaxRate.Text
'Calculate fed tax withholding.
intFedTax = intGrossPay * txtFedTaxRate.Text
' Calculate FICA witholding.
intFICA = intGrossPay * txtFICA.Text
'Calculate net pay.
intNetPay = intGrossPay - (intStateTax + intFedTax + intFICA)
If (intStateTax + intFedTax + intFICA) < intGrossPay Then
' Create a string to display.
strPay = ("Employee number" & (intCount.ToString) & ": " & "Gross pay is " & (intGrossPay.ToString("C")) & ". " &
"State tax withholding is " & (intStateTax.ToString("C")) & ". " & "Federal tax withholding is " & (intFedTax.ToString("C")) &
". " & "FICA withholdings is " & (intFICA.ToString("C")) & ". " & "Net pay is " & (intNetPay.ToString("C")) & ". ")
' Add string to listbox."
lstEmployeePay.Items.Add(strPay)
ElseIf (intStateTax + intFedTax + intFICA) > intGrossPay Then
MessageBox.Show("Error: Withholdings are too much.")
End If
Next
End Sub
End Class
After using a Do-Until Loop and getting the counter to increment, I realized that loop was not beneficial to this project at all. It only allowed user to enter the payroll information for one employee and then copied that information to the other three employees.
So I ended up counting the instances of employer data enter a different way altogether. I added an "Employer Number" textbox and incremented the value by for each button click as shown on this in this youtube tutorial: http://youtu.be/qK45UI3dlP0.
So now the code looks like this:
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intGrossPay As Double ' To hold gross pay.
Dim intStateTax As Double ' To hold state tax withholding.
Dim intFedTax As Double ' To hold fed tax withholding.
Dim intFICA As Double ' To hold FICA withholding.
Dim intNetPay As Double ' To hold net pay.
Dim strPay As String ' To hold output.
If Val(txtEmployeeNumber.Text) < 5 Then
'Calculate gross pay.
intGrossPay = txtHourlyPayRate.Text * txtHoursWorked.Text
'Calculate state income tax withholding.
intStateTax = intGrossPay * txtStateTaxRate.Text
'Calculate fed tax withholding.
intFedTax = intGrossPay * txtFedTaxRate.Text
' Calculate FICA witholding.
intFICA = intGrossPay * txtFICA.Text
'Calculate net pay.
intNetPay = intGrossPay - (intStateTax + intFedTax + intFICA)
If (intStateTax + intFedTax + intFICA) < intGrossPay Then
' Create a string to display.
strPay = ("Employee number" & ": " & (Val(txtEmployeeNumber.Text)) & "Gross pay is " & (intGrossPay.ToString("C")) & ". " &
"State tax withholding is " & (intStateTax.ToString("C")) & ". " & "Federal tax withholding is " & (intFedTax.ToString("C")) &
". " & "FICA withholdings is " & (intFICA.ToString("C")) & ". " & "Net pay is " & (intNetPay.ToString("C")) & ". ")
' Add string to listbox."
lstEmployeePay.Items.Add(strPay)
ElseIf (intStateTax + intFedTax + intFICA) > intGrossPay Then
MessageBox.Show("Error: Withholdings are too much.")
End If
txtEmployeeNumber.Text = Val(txtEmployeeNumber.Text) + 1
End If
End Sub

Display check box selections in one string (Visual Basic)

Trying to get the results of all selected items to display in one message box string. I have this so far, which I know is wrong. If it matters, this list is filled via a text file and objects.
Dim cBike As String = "
For Each cBike In clbBikes.Items
cBike = clbBikes.SelectedItem & ", "
Next
MsgBox(("Your selection of: " & cBike))
Help please, my lecturer is taking forever and helping those who need it more.
You probably meant CheckedItems:
Dim cBike As String = ""
For Each chk As String In clbBikes.CheckedItems
cBike &= chk & ", "
Next
MessageBox.Show("Your selection of: " & cBike)
You need to actually concatenate the strings:
For Each cBike In clbBikes.Items
cBike = cBike + clbBikes.SelectedItem & ", "
Next
You need to then also remove the last comma
If (xml.Length > 2) Then
cBike = cBike.Remove(cBike.Length - 2, 2)
End If