Displaying "amount paid" was not enough on Change Calculator, VB VS2012 - vb.net

I am new to VB and for a class project we are to make a change calculator, similar to the one that a question was asked on here before. I have an amount owed and amount paid label and textbox. If the amount owned is greater than the amount paid, the program should display message to remind the customer and tell them how much more to pay.
I figured it out, but the amount that is still due that is displayed in the message is -1.
Example:
Amount Owed: 25
Amount Paid:10
The message will read, The amount paid is less than what is owed. Please pay $ -1 more.
I'm not sure what I've done wrong, and I'm stuck. Any help will be appreciated!
Option Strict On
Option Explicit On
Public Class Form1
Dim AmountPaid As Double
Dim AmountOwed As Double
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
'input amount owed from OwedMaskedTextBox
'input paid amount from PaidTextBox
AmountOwed = Convert.ToDouble(OwedTextBox.Text)
AmountPaid = Convert.ToDouble(PaidTextBox.Text)
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim dif As Double
Dim result As Double = 0
result = CDbl(AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If CBool(result) Then
AlertLabel.Text = "Amount paid is less than what is owed." &
"Please pay $ " & result & " more."
Else
AlertLabel.Text = ""
End If
'display the result
'let totallabel change text to display the difference
TotalLabel.Text = "Change: " &
dif.ToString()
End Sub
End Class

Change the code in this way
'calculate difference of amount owed and paid
'display an alert message if paid amount is less than what is owed
Dim result As Boolean
result = (AmountPaid < AmountOwed)
dif = AmountPaid - AmountOwed
If result Then
.....
The expression (AmountPaid < AmountOwed) is a boolean expression and you could assign directly to a boolean variable. Then you could test this boolean before displaying your message.
So there is no need of these conversions that introduce errors.

Related

Procedure comparing dates in vb.net doesn't appear to do anything

Pretty much just the title, I've been learning vb for my computer science A-level and ran into some trouble with this exercise. I made a procedure to affect the final cost of an invoice by comparing the current date to the due date, but the due date that I input does not seem to have any effect on the final cost.
Form:
Invoice Form
Task:
Write a program that processes invoices for a company selling a variety of products. Ask the user to enter the unit cost of the product, how many were sold and the date the invoice had to be paid by. A check box should be used to indicate if the product is VAT rated. When these details have been entered the user should click a button. This event should call two general procedures. The first should calculate and return the basic cost of the invoice, including VAT. The second should reduce the basic cost by 10% if the invoice has been paid on time. The final cost should be displayed by the Click event of the button.
Code:
Public Class Form1
Dim invoice As Integer
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim unitCost As Integer = txtCost.Text 'Input cost of product in textbox
Dim unitsSold As Integer = txtUnits.Text 'Input units sold in textbox
Dim dueDate As Date = dtpDueDate.Value 'Input date in date and time picker
Dim VATCheck As Boolean = chkVAT.Checked 'Input VAT rating in checkbox
Call InvoiceProcess(unitCost, unitsSold, VATCheck)
Call DueCheck(dueDate, invoice)
MsgBox(invoice)
End Sub
Sub InvoiceProcess(ByRef price As Integer, ByRef units As Integer, ByRef VAT As Boolean)
If VAT = True Then
invoice = 1.2 * price * units
Else
invoice = price * units
End If
End Sub
Sub DueCheck(ByRef dateDue As Date, ByVal invoice As Integer)
Dim todayDate As Date = Today.Date 'Current date
Dim overDue As Integer = DateTime.Compare(todayDate, dateDue.Date)
If overDue <= 0 Then
invoice = invoice * 0.9
End If
End Sub
End Class
The question says "This event should call two general procedures. The first should calculate and return..." - notice it says "return" - that means that it needs to be a function, not a sub.
Once you've got that fixed, the invoice value can be passed from one method to another in the parameters, so you can remove the Dim invoice As Integer from where it is because it is currently scoped to entire class, which you probably don't want.
Also, invoice should be a Decimal, not an Integer.

How can I calculate the cost of the Loan with the Capital and interest rate? Vba

I’m doing a Intership as a Developer an got a tough exercise. I’ve got a Loan Text and there are 3 Fields blank, the Loan, the Capital and the interest rate. I’ve created already the and it look like this:
Private Sub l_jahre_Click()
End Sub
Private Sub txt_abtrag_Change()
CalculateFormular
End Sub
Private Sub txt_darlehen_Change()
CalculateFormular
End Sub
Private Sub txt_zinssatz_Change()
CalculateFormular
End Sub
Private Sub CalculateFormular()
If (validate()) Then
Debug.Print "Success"
End If
End Sub
Private Function validate() As Boolean
validate = True
On Error GoTo x
a = CDbl(txt_abtrag.Value) + CDbl(txt_darlehen.Value) + CDbl(txt_zinssatz.Value)
Exit Function
x:
validate = False
End Function
Public Sub test2()
'Debug.Print txt_zinssatz.Value
l_zinsen.Caption = "inf."
End Sub
Don’t mind the Value of them xd
And now I Need to calculate, like I said, the cost of the Loan with the Capital and interest rate.
I Need to fill it up and it Looks like this.
Public Function GetTotalCost(ByVal capital As Double, ByVal rate As Double) As Double
GetTotalCost = 0
End Function
Public Function GetRentTime(ByVal capital As Double, ByVal rate As Double, ByVal monthPay As Double) As Double
GetRentTime = 0
End Function
please don’t say the full Code or the full answer I just Need some help to understand and what method I should use.
Thank you for your help.
The financial formulae below each solve one financial argument (PV, FV, PMT, NPER) in terms of the others, using (pmt*nper)+pv+fv = 0 if the rate is 0, and pv*((1+rate)^nper)+pmt*(1+rate*type)*((1+rate)^nper-1)/rate+fv = 0 otherwise, where:
• pv is the present value of a loan or investment, and represents the current value of a series of future payments. For example, when you borrow money, the amount you owe is the present value to the lender.
• fv is the future value, or a cash balance of the loan or investment after the last payment is made.
• rate is the interest rate per period.
• nper is the total number of payment periods over the life of the loan or investment.
• pmt is the fixed instalment paid in each period. The instalment amount usually includes components to cover both principal and interest but may not include loan fees etc. This is negative if you're borrowing, because it represents money you would pay (i.e. a negative cash flow).
• type is the number 0 or 1 and indicates when instalments are paid. 0 indicates payments are made at the end of the period, 1 indicates payments are made at the start of the period. Equally, some loans charge interest on the basis of the amount outstanding at the beginning of the period, whilst others charge interest on the basis of the amount outstanding at the end of the period.
Solving for the future value, the formula is:
fv=-if(rate=0,pmt*nper+pv,(pv*((1+rate)^nper)+pmt*(1+rate*type)*((1+rate)^nper-1)/rate))
Solving for the present value, the formula is:
pv=-if(rate=0,pmt*nper+fv,(fv+pmt*(1+rate*type)*((1+rate)^nper-1)/rate)/((1+rate)^nper))
Solving for the payment value, the formula is:
pmt=-if(rate=0,(pv+fv)/nper,(pv*((1+rate)^nper)+fv)/((1+rate*type)*((1+rate)^nper-1)/rate))
Solving for the number of periods, the formula is:
nper=-if(rate=0,(pv+fv)/pmt,(log(1+(pv+pmt*type)/pmt*rate)-log(1+(fv+pmt*type)/pmt*rate))/log(1+rate))
Solving for the interest rate, the formula is:
rate=(fv/pv)^(1/nper)-1
provided pmt is 0. Otherwise, you can only solve for the interest rate through iteration (eg using one of the above formulae).

Expression is not a method in Visual Basic.net

I have a problem for this code. lstTotal is the error. It says Expressions is not a method for the lstTotal. Im not very knowledgable in coding yet so any help would be appreciated.
Private Sub UpdateTotal()
' Clear the previous subtotal, tax and total
lstTotal.Items.Clear()
' Compute and display the subtotal
lstTotal.Items.Add("SUB TOTAL = ")(subtotal.ToString("C"))
' Compute and Display the tax
Tax = subtotal * TAX_RATE
lstTotal.Items.Add(" TAX=" & Tax.ToString("C"))
' Compute and display the total
lstOrderReceipt.Items.Add("---------------")
End Sub
This doesn't make sense:
lstTotal.Items.Add("SUB TOTAL = ")(subtotal.ToString("C"))
Presumably you mean this:
lstTotal.Items.Add("SUB TOTAL = " & subtotal.ToString("C"))
The error message is saying that you are doing this:
Expression(subtotal.ToString("C"))
which is how you would call a method but what you have in place of Expression, i.e. lstTotal.Items.Add("SUB TOTAL = ") does not evaluate to a method so your code doesn't make sense.

VB - Negative Number and Conditional Statement

Back again with another noob question that is bugging the crap out of me. I spent 2 days trying figure this one out. It seems that me and VB and negative numbers always have a misunderstanding.
I got everything else in the program for a fat percentage calculator to work except the conditional statement that SHOULD print out an error message if either the double conversion of two textbox strings is less than zero. However, even though I enter negative numbers for both when testing, the program skips over my Else error statement and calculates the two negative numbers anyway and gets some wholly ridiculous fat percentage number. It doesn't even seem as if it's just going through with the expressions if the "If-Then" part of the code as I did the math and the percentage answer does not match up.
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Declare variables
Dim dblCaloriesInFood As Double
Dim dblGramsOfFat As Double
Dim dblPercentageOfCaloriesFromFat As Double
Dim dblCaloriesFromFat As Double
'Always initialize lblLowInFat message as not visible when button is clicked
lblLowInFat.Visible = False
Try
'Converting textbox strings to double.
dblCaloriesInFood = CDbl(txtCaloriesInFood.Text)
dblGramsOfFat = CDbl(txtGramsOfFat.Text)
If dblCaloriesInFood Or dblGramsOfFat > 0 Then
'Calculate Calories from fat
dblCaloriesFromFat = dblGramsOfFat * 9
'Calculate percentage of calories from fat
dblPercentageOfCaloriesFromFat = dblCaloriesFromFat / dblCaloriesInFood
'Display percentage of calories from fat
If dblPercentageOfCaloriesFromFat >= 0 Then
lblMessage.Text = dblPercentageOfCaloriesFromFat.ToString("p")
Else
lblMessage.Text = String.Empty
End If
'Display low fat message
If dblPercentageOfCaloriesFromFat <= 0.3 And dblPercentageOfCaloriesFromFat > 0 Then
lblLowInFat.Visible = True
End If
Else
'really tried to make this message work but couldn't figure it out.
'why does it only display this message when zero is entered and not when
'negative numbers are entered. instead it just calculates the negative numbers
'as if they were whole positive numbers or something, not sure because the percentage
'is way off the charts when i enter negative numbers. can't figure this out.
MessageBox.Show("Either the calories or fat grams were incorrectly entered")
txtCaloriesInFood.Text = String.Empty
txtGramsOfFat.Text = STring.Empty
txtCaloriesInFood.Focus()
End If
Catch
'error message for invalid input
MessageBox.Show("Please enter a numeric value for calories in food & number of fat grams.")
txtCaloriesInFood.Focus()
End Try
End Sub
Your If statement is wrong. First, you need to test the two values separately. Second, you want both values to be greater than zero, so you should use And instead of Or (which means only one has to be greater than zero).
If dblCaloriesInFood > 0 And dblGramsOfFat > 0 Then

Need help correcting this VB.net

Dim dbBorrow As Double
dbBorrow = txtBorrow.Text
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
ElseIf dbBorrow = "" Then
MessageBox.Show("Pls Enter the amount you want to borrow")
My question says that if i want to obtain a loan the val should be inbetween 500000 and 7000000, so if its less than 500000 then i used a message box to say the loan cannot be obtain i used the same thing for more than 70000000. but if the textbox is left empty i wanted to display a message saying pls enter a val. i tried this error appears "Conversion from string "" to type 'Double' is not valid."
You are mixing strings and double. You should enable option strict on, this will help you understand what is happening.
If you properly convert your string to a double, you can set your double to NaN if it's not a valid number (this won't just work for empty string, but also work if you write letters).
Dim dbBorrow As Double
If Not Double.TryParse(txtBorrow.Text, dbBorrow) Then
dbBorrow = Double.NaN
End If
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
ElseIf Double.IsNaN(dbBorrow) Then
MessageBox.Show("Pls Enter the amount you want to borrow")
Else
' ...
End If
I made a few adjustments to your code please see below... Using the TryParse will not thrown an exception when not a double, it would return false...
Dim dbBorrow As Double = 0
If Double.TryParse(txtBorrow.Text, dbBorrow) Then
If dbBorrow < 500000 Then
MessageBox.Show("Lowest Amount which can be borrow is RS.500000")
ElseIf dbBorrow > 7000000 Then
MessageBox.Show("Maximum amount which can be borrowed is RS.7000000")
End If
Else
MessageBox.Show("Pls Enter the amount you want to borrow")
End If