Two balance won't add up if both checkboxes are checked - vb.net

I am writing a program that should calculate the balance with the given information (Which checkbox they choose (Savings (7%), Corporate(5%), or both, then the year they choose (2015, 2016, 2017), and lastly the amount they put in when cued to enter balance (And that is based on what type of account they choose in the first step). I have gotten all of the totals to show up correctly, except for when they choose both account types (Savings and Corporate). To me their should be a line that just adds the two totals if both are chosen, but that isn't the case. At least for me it isn't.
The total I get if I enter the balance of $2000 for savings and choose year 2015 the total is $2289.80 which is correct and then if I choose 2015 for the corporate account and enter $1000 the total is $1102.50. So if I chose both of the accounts and entered the same numbers but checked both checkboxes I get $3434.70, but I should get $3392.30!
Here is the code I have, any help would be much appreciated! ( I think it might literally be just one line of code and it is killing me!)
Public Class Form1
Private Sub btnMediaEstimatedFund_Click(sender As Object, e As EventArgs) Handles btnMediaEstimatedFund.Click
Dim interestRate, initialBalanceSavings, initialBalanceCorporate, finalBalance, year, theYear, subTotal As Double
Dim savingsInterestRate As Double = 0
Dim corporateInterestRate As Double = 0
Dim savingsSubTotal As Double = 0
Dim corporateSubTotal As Double = 0
txtBoxEstimatedBudget.Enabled = False
txtBoxAgenciesNeeded.Enabled = False
If radButtonTraditional.Checked Then
txtBoxAgenciesNeeded.Text = 3
ElseIf radButtonEMedia.Checked Then
txtBoxAgenciesNeeded.Text = 2
End If
If checkBoxSavings.Checked Then
savingsInterestRate = 0.07
ElseIf checkBoxCorporate.Checked Then
corporateInterestRate = 0.05
End If
If checkBoxSavings.Checked = False And checkBoxCorporate.Checked = False Then
MsgBox("Please chose an account type to proceed!", MsgBoxStyle.Critical, "Error")
End If
If radButton2015.Checked Then
theYear = 2015
ElseIf radButton2016.Checked Then
theYear = 2016
ElseIf radButton2017.Checked Then
theYear = 2017
End If
Dim inputtedData As String
If checkBoxSavings.Checked Then
Do
inputtedData = InputBox("Please enter a balance for SAVINGS account between $500.00 and $3000.00", "Initial Savings Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to cancel calculation!")
Exit Sub
Else
initialBalanceSavings = CType(inputtedData, Single)
If initialBalanceSavings > 3000 Or initialBalanceSavings < 500 Then MsgBox("Please enter a balance for SAVINGS account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceSavings >= 500 And initialBalanceSavings <= 3000
End If
If checkBoxCorporate.Checked Then
Do
inputtedData = InputBox("Please enter a balance for CORPORATE account between $500.00 and $3000.00", "Initial Corporate Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to Cancel calculation!")
Exit Sub
Else
initialBalanceCorporate = CType(inputtedData, Single)
If initialBalanceCorporate > 3000 Or initialBalanceCorporate < 500 Then MsgBox("Please enter a balance for CORPORATE account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceCorporate >= 500 And initialBalanceCorporate <= 3000
End If
savingsSubTotal = initialBalanceSavings
corporateSubTotal = initialBalanceCorporate
For year = 2013 To theYear - 1
If savingsInterestRate > 0 Then
savingsSubTotal = savingsSubTotal * (1 + savingsInterestRate)
End If
If corporateInterestRate > 0 Then
corporateSubTotal = corporateSubTotal * (1 + corporateInterestRate)
End If
Next
finalBalance = savingsSubTotal + corporateSubTotal
txtBoxEstimatedBudget.Text = FormatCurrency(finalBalance)
End Sub

I believe the erroneous logic is in this block of code:
finalBalance = initialBalanceSavings + initialBalanceCorporate
For year = 2013 To theYear - 1
subTotal = finalBalance * (1 + interestRate)
finalBalance = subTotal
Next
Combined with this block of code:
If checkBoxSavings.Checked Then
interestRate = 0.07
ElseIf checkBoxCorporate.Checked Then
interestRate = 0.05
End If
In the above, even if something checks both checkboxes the interest rate is set at 0.07 so in your loop if someone calculates 2015 you will do something like give you a final total of: 3000 * 1.07 * 1.07, whereas you really want (2000 * 1.07 * 1.07) + (1000 * 1.05 * 1.05)
In essence because you only use one variable to hold the interest rate (as well as only having one variable to hold sub-totals) your code cannot account properly for a scenario where someone selects both accounts. I would suggest having 2 variables to hold the interest rates:
Dim savingsInterestRate as Double = 0
Dim corporateInterestRate as Double = 0
And 2 variables to hold the sub-totals:
Dim savingsSubTotal as Double = 0
Dim corporateSubTotal as Double = 0
And in your For loop do:
savingsSubTotal = initialBalanceSavings
corporateSubTotal = initialBalanceCorporate
For year = 2013 To theYear - 1
If savingsInterestRate > 0 Then
savingsSubTotal = savingsSubTotal * (1 + savingsInterestRate)
End If
If corporateInterestRate > 0 Then
corporateSubTotal = corporateSubTotal * (1 + corporateInterestRate)
End If
Next
finalBalance = savingsSubTotal + corporateSubTotal
And change your interest rate check to:
If checkBoxSavings.Checked Then
savingsInterestRate = 0.07
End If
If checkBoxCorporate.Checked Then
corporateInterestRate = 0.05
End If
So you can account for the person's selection (using the ElseIf means that if they check both, it will discard the corporate rate since checkBoxSavings.Checked is already true sp it never falls into the ElseIf block)

Related

How to find federal taxes based on salary ranges

I'm designing a software that does basic payroll for a school project. I'm stuck on this one part where I have to figure out what the federal tax will be based on the employee salary. This is the chart that tells you the rate of the tax based on salary range.
I tried this code,
Dim federaltaxrate As Integer
Dim federaltax = (salary.Text * federaltaxrate)
If salary.Text >= 0 Then
If salary.Text <= 50 Then
federaltaxrate = 0
End If
ElseIf salary.text <= 500 Then
If salary.Text >= 50 Then
federaltaxrate = 0.1
End If
ElseIf salary.text <= 2500 Then
If salary.Text >= 500 Then
federaltaxrate = 45 + 0.15 * salary.Text - 500
End If
ElseIf salary.text <= 5000 Then
If salary.Text >= 2500 Then
federaltaxrate = 345 + 0.2 * salary.Text - 2500
End If
ElseIf salary.text >= 5000 Then
federaltaxrate = 845 + 0.25 * salary.Text - 5000
End If
Else
End If
I have a listbox that shows other information as well but this is what I used to show the calculated info in the listbox.
ListBox1.Items.Add("Federal Tax: $" + federaltax.ToString)
When I run this code and input in a random salary, the federal tax shows up as 0.
Do I need to convert the salary into weekly gross pay, if so how would I go on about writing the code that finds the federal tax rate based on the salary and it's range.
You might be having trouble with order of precedence of the arithmetic operations. I think a Select Case is cleaner.
Private Function GetFederalTax(GrossPay As Decimal) As Decimal
Dim FederalTax As Decimal
Select Case GrossPay
Case < 50
FederalTax = 0
Case < 500
FederalTax = CDec((GrossPay - 51) * 0.1)
Case < 2500
FederalTax = CDec(((GrossPay - 500) * 0.15) + 45)
Case < 5000
FederalTax = CDec(((GrossPay - 2500) * 0.2) + 345)
Case Else
FederalTax = CDec(((GrossPay - 5000) * 0.25) + 845)
End Select
Return FederalTax
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim grossPay As Decimal
If Decimal.TryParse(TextBox1.Text, grossPay) Then
Dim tax = GetFederalTax(grossPay)
Debug.Print($"Gross {grossPay} Tax {tax}")
ListBox1.Items.Add(String.Format("Federal Tax {0}, Gross Pay {1}", tax, grossPay)) '***EDIT***
Else
MessageBox.Show("Please enter a valid number.")
End If
End Sub
The sample test produced the following in the Immediate Window.
Gross 45 Tax 0
Gross 700 Tax 75
Gross 8000 Tax 1595
Gross 2501 Tax 345.2
Gross 2800 Tax 405
Firstly, your Boolean logic is all wrong. If the salary value was 51, you'd satisfy the first outer condition (>= 0) and then fail the first inner condition (<= 50). There would not be any further comparisons performed - which you would know if you'd debugged - so no tax calculation would ever be performed.
Secondly, your calculations are OK but you're misusing the results. Those calculation get the amount of tax to be paid, not the rate. The rates are 10%, 15%, 20% and 25%, which are already contained in your calculations. Get rid of that second variable and just assign the results of appropriate calculations to the one variable.
I would do it like this:
Dim salaryAmount = CDec(salary.Text)
Dim taxAmount As Decimal = Decimal.Zero
If salaryAmount > 5000D Then
taxAmount = 845D + 0.25D * (salaryAmount - 5000D)
ElseIf salaryAmount > 2500D Then
taxAmount = 345D + 0.2D * (salaryAmount - 2500D)
ElseIf salaryAmount > 500D Then
taxAmount = 45D + 0.15D * (salaryAmount - 500D)
ElseIf salaryAmount > 50D Then
taxAmount = 0.1D * (salaryAmount - 50D)
End If
'Use taxAmount here.
This uses appropriate data types throughout, i.e. it does not perform arithmetic on String values and it uses Decimal for currency values. The D suffix on the literals forces them to be type Decimal rather than Integer or Double.
It also works from biggest to smallest to simplify the Boolean expressions.
The Nested If should be combined like below as it is missing few cases
If salary.Text >= 0 And salary.Text <= 50 Then
federaltaxrate = 0
ElseIf salary.text <= 500 And salary.Text >= 50 Then
federaltaxrate = 0.1
ElseIf salary.text <= 2500 AND salary.Text >= 500 Then
federaltaxrate = 45 + 0.15 * salary.Text - 500
End If

Input validation and repetition in vba

I have the following code and I would like help in 4 areas:
Did I validate the inputbox correctly? It should only take positive numerical variables.
How can I let the input box accept both input with, and without, symbols such as ($)?
How can I link the code so that it can directly request another number if the user has entered a negative non numeric number?
How can I repeat the procedure in the loop directly without repeating the whole code?
Option Explicit
Sub IncomeSalaryCalculation()
Dim strSalary As String
Dim dblTaxableSalary As Double
Dim dblTax As Double
Dim dblSalaryAfterTax As Double
Dim strOutput As String
Dim SalaryCalculationRequest As VbMsgBoxResult
strSalary = InputBox("Please indicate your salary", "Salary Calculation")
If Not IsNumeric(strSalary) Then
MsgBox "This is no number! Please enter a non-negatif number", vbOKOnly, "Error"
ElseIf strSalary < 0 Then
MsgBox "You should enter a positive number", vbOKOnly, "Error"
Else
dblTaxableSalary = CDbl(strSalary)
Select Case dblTaxableSalary
Case Is >= 151000
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (150000 - 37400) * 0.5 + (dblTaxableSalary - 150000) * 0.5
Case Is >= 37401
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (dblTaxableSalary - 37400) * 0.4
Case Is >= 2441
dblTax = 2440 * 0.1 + (dblTaxableSalary - 2440) * 0.2
Case Else
dblTax = 2440 * 0.1
End Select
dblSalaryAfterTax = dblTaxableSalary - dblTax
strOutput = "The amount of income tax is " & dblTax & vbNewLine & "Your salary after tax is " & dblSalaryAfterTax
MsgBox strOutput, vbOKOnly, "Final Salary"
Do
SalaryCalculationRequest = MsgBox("Do you want to calculate the tax of a new income?", vbYesNo, "New income tax salary calculation")
If SalaryCalculationRequest = vbYes Then
strSalary = InputBox("Please indicate your salary", "Salary Calculation")
dblTaxableSalary = CDbl(strSalary)
Select Case dblTaxableSalary
Case Is >= 151000
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (150000 - 37400) * 0.5 + (dblTaxableSalary - 150000) * 0.5
Case Is >= 37401
dblTax = 2440 * 0.1 + (37400 - 2440) * 0.2 + (dblTaxableSalary - 37400) * 0.4
Case Is >= 2441
dblTax = 2440 * 0.1 + (dblTaxableSalary - 2440) * 0.2
Case Else
dblTax = 2440 * 0.1
End Select
dblSalaryAfterTax = dblTaxableSalary - dblTax
strOutput = "The amount of income tax is " & dblTax & vbNewLine & "Your salary after tax is " & dblSalaryAfterTax
MsgBox strOutput, vbOKOnly, "Final Salary"
Else
MsgBox "Glad to serve you"
End If
Loop Until SalaryCalculationRequest = vbNo
End If
End Sub
This should answer your questions without delving into all your code. Tested.
Sub getInput()
Dim ans As String
Do
ans = InputBox("Please indicate your salary", "Salary Calculation")
Loop Until isValid(ans)
''{{{{{{{{
''Do what you need here with the user input (stored in *ans* variable)
''}}}}}}}}
End Sub
Function isValid(ans As String) As Boolean
Dim cleanAns As variant
cleanAns = IIf(ans Like "*$*", Replace(ans, "$", ""), ans)
isValid = IsNumeric(cleanAns) And cleanAns > 0
If Not isValid Then MsgBox "only positive numbers allowed"
End Function

How to Loop through a If condition untill the user enter a required value, in Visual Basic

Console.WriteLine("Please Enter the number")
Dim number As Integer = Console.ReadLine()
If (number=< 40) Then
number = number* 10
ElseIf (number=< 150) Then
number= number* 15
Else
number= number* 26
End If
Console.WriteLine(number)
Dim total As Integer
Dim vALUE As Integer
Console.WriteLine("Please, type 1 for x . Type 2 for y. Type 3 z")
vALUE = Console.ReadLine()
If vALUE = 1 Then
Console.WriteLine("x")
total = number* (106 / 100)
ElseIf vALUE = 2
Console.WriteLine("y")
total = number* (112 / 100)
ElseIf uSERvALUE = 3
Console.WriteLine("z")
total = number* (116 / 100)
Else
Console.WriteLine("Sorry please re-enter the value")
vALUE = Nothing
End If
End While
Please tell me how to repeat the if condition. In the else line I have displayed to the user to re-enter the value. Therefore I need to repeat the if condition until the value is 1 or 2 or 3.Please explain how to do I'm a newbie.
You can use infinite While-loop ,and put "Exit While" on the end of conditional statement you agreed , so there are few ways out from infinite loop.
For example , on your code:
Console.WriteLine("Please Enter the number")
Dim number As Integer = Console.ReadLine()
If (number=< 40) Then
number = number* 10
ElseIf (number=< 150) Then
number= number* 15
Else
number= number* 26
End If
Console.WriteLine(number)
Dim total As Integer
Dim vALUE As Integer
'infinite loop until user input 1,2 or 3
While True
Console.WriteLine("Please, type 1 for x . Type 2 for y. Type 3 z")
vALUE = Console.ReadLine()
If vALUE = 1 Then
Console.WriteLine("x")
total = number* (106 / 100)
Exit While 'condition matched , break from While
ElseIf vALUE = 2
Console.WriteLine("y")
total = number* (112 / 100)
Exit While 'condition matched , break from While
ElseIf uSERvALUE = 3
Console.WriteLine("z")
total = number* (116 / 100)
Exit While 'condition matched , break from While
Else
Console.WriteLine("Sorry please re-enter the value")
vALUE = Nothing
End If
End While
'do further more you need

Getting balance from code in button

I am having a little bit of trouble calculating the balance in my code.
In this program (balance = balance * (1 + interestRate). The thing is that we are in 2013 and the balance will be calculated for the year 2015-2017, which is picked by a checkbox the user clicks in the program, and also the user picks what type of account they will have (Ie Savings: 7% interest, Corporate: 5% interest).
They will then click the mediaEstimatedFund button and it will ask them to enter a balance for the type of account that they chose (Savings, Corporate, or both). It should then calculate the balance for the (Year, Account, and Balance amount) that they chose.
Here is the code I have and it is not giving me the right balances (Example: If the user chose $2000.00, a Savings account at 7% and the year 2016, it should give me the estimated budget of $2621.60), but it is not!
Year Savings Account Corporate Account Saving + Corporate
2013 $2000.00 $1000.00 $3000.00
2014 $2140.00 $1050.00 $3190.00
2015 $2289.8 $1102.5 $3392.3
2016 $2450.086 $1157.625 $3607.711
2017 $2621.59202 $1215.50625 $3837.09827
Public Class Form1
Private Sub btnMediaEstimatedFund_Click(sender As Object, e As EventArgs) Handles btnMediaEstimatedFund.Click
Dim interestRate, initialBalanceSavings, initialBalanceCorporate, finalBalance, theYear, balance, subTotal As Double
txtBoxEstimatedBudget.Enabled = False
txtBoxAgenciesNeeded.Enabled = False
If radButtonTraditional.Checked Then
txtBoxAgenciesNeeded.Text = 3
ElseIf radButtonEMedia.Checked Then
txtBoxAgenciesNeeded.Text = 2
End If
If checkBoxSavings.Checked Then
interestRate = 0.07
ElseIf checkBoxCorporate.Checked Then
interestRate = 0.05
ElseIf checkBoxCorporate.Checked And checkBoxSavings.Checked Then
interestRate = 0.12
End If
If radButton2015.Checked Then
theYear = 2015
End If
If radButton2016.Checked Then
theYear = 2016
End If
If radButton2017.Checked Then
theYear = 2017
End If
Dim inputtedData As String
If checkBoxSavings.Checked Then
Do
inputtedData = InputBox("Please enter a balance for SAVINGS account between $500.00 and $3000.00", "Initial Savings Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to cancel calculation!")
Exit Sub
Else
initialBalanceSavings = CType(inputtedData, Single)
If initialBalanceSavings > 3000 Or initialBalanceSavings < 500 Then MsgBox("Please enter a balance for SAVINGS account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceSavings >= 500 And initialBalanceSavings <= 3000
End If
If checkBoxCorporate.Checked Then
Do
inputtedData = InputBox("Please enter a balance for CORPORATE account between $500.00 and $3000.00", "Initial Corporate Balance", "0.00")
If inputtedData = "" Then
MsgBox("User chose to Cancel calculation!")
Exit Sub
Else
initialBalanceCorporate = CType(inputtedData, Single)
If initialBalanceCorporate > 3000 Or initialBalanceCorporate < 500 Then MsgBox("Please enter a balance for CORPORATE account equal to or above $500.00 and no more than $3000.00", MsgBoxStyle.Critical, "Error")
End If
Loop Until initialBalanceCorporate >= 500 And initialBalanceCorporate <= 3000
End If
finalBalance = initialBalanceSavings + initialBalanceCorporate
For theYear = 2013 To 2017
subTotal = finalBalance * (1 + interestRate)
finalBalance = subTotal
Next
txtBoxEstimatedBudget.Text = FormatCurrency(finalBalance)
End Sub
I wasn't allowed to edit Zafs answer to include the extra line, so here is my take. The important point being that the initialization of finalBalance is outside of the for-loop.
finalBalance = initialBalanceSavings + initialBalanceCorporate
For theYear = 2013 To 2016
subtotal = finalBalance * (1 + interestRate)
finalBalance = subTotal
Next
For TheYear = 2013 to 2016
SubTotal = balance * (1 + interestRate)
balance = SubTotal
Next
UPDATE
The code block above is just to give you an IDEA of HOW to do the loop and what should be calculated INSIDE the loop. To get the actual ANSWER you MUST remember that 2013 is the CURRENT year so you would not ACTUALLY calculate the interest for that year. And key to the way in which you accomplish this is the formatting of your loop, which in reality should begin the FOLLOWING year.
For Year = 2013 + 1 to 2016
'blah blah blah
Next

Visual Basic - "If" Statements Not Showing Result In Label

I'm working on an assignment where the program needs to calculate and display the total cost for shipping a package, based on weight and whether it is being shipped to Continental U.S., Alaska, or Hawaii. When I click the Calculate button, though, the label that is supposed to display the total is left blank. I've looked through this and tried placing the calculation in different parts/at the end of the "If" statements. Here's what I have thus far, any help would be appreciated:
Dim decWeight As Decimal
Dim decTotalCost As Decimal
Dim decDestination As Decimal
Dim decRate As Decimal
If IsNumeric(txtWeight.Text) Then
decWeight = Convert.ToDecimal(txtWeight.Text)
If decWeight <= 30 > 0 Then
If radContinental.Checked Then
decDestination = 1
ElseIf radHawaii.Checked Then
decDestination = 1.2
ElseIf radAlaska.Checked Then
decDestination = 1.26
End If
If decWeight <= 2 Then
decRate = 3.69
ElseIf decWeight <= 4 > 2 Then
decRate = 4.86
ElseIf decWeight <= 6 > 4 Then
decRate = 5.63
ElseIf decWeight <= 8 > 6 Then
decRate = 5.98
ElseIf decWeight <= 10 > 8 Then
decRate = 6.28
ElseIf decWeight <= 30 > 10 Then
decRate = 15.72
End If
decTotalCost = decRate * decDestination
lblTotalCost.Text = decTotalCost.ToString("C")
ElseIf decWeight <= 0 Then
MsgBox("Please Enter a Positive Weight.", , "Input Error")
ElseIf decWeight > 30 Then
MsgBox("You Have Entered " & decWeight.ToString() & ". Please Enter a Weight Under 30 Pounds", , "Input Error")
End If
ElseIf txtWeight.Text = "" Then
MsgBox("Please Enter the Weight", , "Input Error")
Else : MsgBox("Please Enter a Number", , "Input Error")
End If
You should try this if statement: If decWeight <= 30 and decWeight > 0 Then
This will check if the decWeight is less than or equal to 30 and make sure that it is 'non-zero' Hope this helps :-)