Syntax error when multiplying variables in VB.NET - vb.net

I'm trying to multiply two variables within VB Studio, however I am getting a syntax error when trying to do this.
(Quantity * ItemCost) gives me a syntax error on the first bracket, and removing the brackets gives me the error that method arguments must be enclosed in parenthesis.
Sorry if this was rather vague or really obvious, I am new to programming in general and am doing my best to make simple programs. I know my code is far from the most efficient but it's the best I can do at the moment.
The whole of my code is below :
Public Class Form1
Dim CustomerName As String
Dim Pensioner As Boolean
Dim Takeout As Boolean
Dim Items(4) As Array
Dim CostOfItems(4) As Array
Dim Alpha As Integer = 0
Dim Quantity As Integer
Dim ItemCost As Integer
Private Sub txtName_TextChanged(sender As Object, e As EventArgs) Handles txtName.TextChanged
CustomerName = txtName.Text
End Sub
Private Sub cboItemName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboItemName.SelectedIndexChanged
If cboItemName.Text = "Tea" Then
txtItemPrice.Text = "£0.50"
ElseIf cboItemName.Text = "Coffee" Then
txtItemPrice.Text = "£0.70"
ElseIf cboItemName.Text = "Orange Juice" Then
txtItemPrice.Text = "£0.80"
ElseIf cboItemName.Text = "Apple Juice" Then
txtItemPrice.Text = "£0.80"
ElseIf cboItemName.Text = "Potato" Then
txtItemPrice.Text = "£1.00"
End If
ItemCost = txtItemPrice.Text
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
Quantity = txtQuantity.Text
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If chxPension.Checked = True Then
Pensioner = True
chxPension.Hide()
End If
If cbxTakeOut.Checked = True Then
TakeOut = True
cbxTakeOut.Hide()
End If
Quantity * ItemCost
txtQuantity.Text = ""
cboItemName.Text = ""
Alpha += 1
txtName.ReadOnly = True
End Sub
End Class
(I have now changed the ItemCost value to not include a £ or . , however I am still getting a syntax error on the bracket)

The problem with your code is that you are not assigning the result of the multiplication to any variable. Some languages permit that (calculating a value and throwing it away), but apparently VB.NET doesn't. It is trying to save you from a common programmer mistake.
Do it like this instead:
Dim TotalCost As Integer = Quantity * ItemCost
The result of the multiplication will now be stored in the variable TotalCost, which you can use for whatever you need.
Of course, you could also store the result of the calculation in one of the operand variables (assuming, of course, it is not a constant). In this case, judging from the names of the variables, it doesn't make much sense, but sometimes it is appropriate:
ItemCost = Quantity * ItemCost ' probably wrong, but syntactically legal

You also need to declare your variables correctly.
item cost can not be integer.
Item cost should be something like double or decimal
Dim TotalCost as Decimal = Quantity * ItemCost

Could you please remove the £ in your txtItemPrice.Text?
Replace this in your existing codes:
ItemCost = cInt(txtItemPrice.Text)
Quantity = cInt(txtQuantity.Text)
This is to convert the Strings (.text) into Integer
For the computation of Total Cost:
Dim Total As Integer = Quantity * ItemCost
Please Take Note:
Integer data types cannot hold values with decimal. Use Double instead.

Related

I can't find the reason for InvalidCastException

I am trying to make an app like an online shop for my project. The code is fine at first(at least for me since there's no errors indications)
But when I run it and press the "Add to Cart" button, it says InvalidCastException and says that I'm trying to convert a string to double even though I am not converting anything
This is what I have so far
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim prditem As ListViewItem
Dim price, cartprice As Integer
Dim product As String
If clbParts.SelectedItem = 0 Then
product = "Power Supply"
price = 1
End If
If clbParts.SelectedItem = 1 Then
product = "CPU"
price = 2
End If
....
If rdo512gb.Checked = True Then
product = "Hard Drive (512GB)"
price = 11
End If
If rdo1tb.Checked = True Then
product = "Hard Drice (1TB)"
price = 12
End If
cartprice = Price * numQuantity.Text
prditem = lvCart.Items.Add(product)
With prditem
.SubItems.Add(numQuantity.Text)
.SubItems.Add(cartprice)
End With
If numQuantity.Text = "0" Then
MessageBox.Show("Please put the number of items you want to add", "Cart Error")
End If
MessageBox.Show("Item/s is/are added to your cart", "Cart")
numQuantity.Text = "0"
End Sub
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
Dim total As Integer = 0
For i As Integer = 0 To lvCart.Items.Count - 1
Dim quantity = CInt(lvCart.Items(i).SubItems(1).Text)
Dim price = CInt(lvCart.Items(i).SubItems(2).Text)
total += quantity + price
Next
txtTotal.Text = total.ToString("N2")
End Sub
Private Sub cboPayment_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPayment.SelectedIndexChanged
If cboPayment.SelectedItem = 0 Then
Label10.Enabled = True
cboOnline.Enabled = True
Else
Label10.Enabled = False
cboOnline.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("Your items are being delivered in " + txtHomeAddress.Text + ", " + txtAddress.Text + "\n Please wait for the text confirmation", "Cart Error")
End Sub
End Class
Do yourself a favor and watch a YouTube video on how to debug in Visual Studio!
What you need to do is put a Breakpoint on this line:
cartprice = Price * numQuantity.Text
convert a string to double
You're multplying a number by a String! You want to do something like this:
cartprice = Price * Convert.ToDouble(numQuantity.Text)
I'd personally do a double.TryParse to see if its valid and use the output value when performing the operation.
PS: As a challenge to yourself, try and move all the code logic to a Business Logic class, then use Bingings/BindingControls so the Presentation layer is separated from the logic. That way you can Unit Test the business logic layer!

How do I output the average of a set of numbers in a txt file?

I have this so far but it just outputs 0
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim inFile As IO.StreamReader
Dim intBill As Integer
Dim avg As Integer
Dim trueAvg As Integer
If IO.File.Exists("monthlyBills.txt") Then
inFile = IO.File.OpenText("monthlyBills.txt")
Do Until inFile.Peek = -1
Integer.TryParse(inFile.ReadLine, intBill)
avg += intBill
Loop
inFile.Close()
trueAvg = CInt(avg / 12D)
lblAvg.Text = trueAvg.ToString()
Else
MessageBox.Show("Cannot find the file.", "monthlyBills",
MessageBoxButtons.OK, MessageBoxIcon.Information)
lblAvg.Text = "N/A"
End If
End Sub
End Class
Here is the "monthlyBills.txt" text file:
141.71
156.75
179.25
141.71
130.19
115.05
95.65
86.78
85.45
79.99
98.45
126.78
The problem is that none of the values in your text file is an integer and yet, you're trying to parse them as integers. You should use a Decimal type instead.
One more thing, whenever you use a .TryParse() method, you probably want to check its return value to make sure whether or not the parsing was successful. An If statement would help in this case.
This should work fine:
Dim inFile As IO.StreamReader
Dim intBill As Decimal
Dim avg As Decimal
Dim trueAvg As Integer
If IO.File.Exists(filePath) Then
inFile = IO.File.OpenText(filePath)
Do Until inFile.Peek = -1
If Decimal.TryParse(inFile.ReadLine, intBill) Then
avg += intBill
Else
' TODO: decide what you should do if a line isn't a decimal value.
End If
Loop
inFile.Close()
trueAvg = CInt(avg / 12D)
lblAvg.Text = trueAvg.ToString()
Else
MessageBox.Show("Cannot find the file.", "monthlyBills",
MessageBoxButtons.OK, MessageBoxIcon.Information)
lblAvg.Text = "N/A"
End If
Notes:
I changed the type of both inBill and avg to Decimal but kept trueAvg as in integer just in case you need that end value to be rounded. If you don't have a specific reason for that, you should use a Decimal instead and get rid of the CInt.
Floating numbers in .NET can be represented in two different categories of types; a binary representation (like Single or Double types), and a decimal representation (the Decimal type). For your particular situation, I suggested using Decimal because you seem to be dealing with prices and Decimal would be more suitable. You may read more about the difference in this post.
To use a method that doesn't have a .TryParse you must be very sure that each line in the text file is a number.
.ReadAllLines returns an array where each element is a line in the text file.
Next we use a bit of Linq to change each line (which is a string) to a Decimal value. The .Trim removes any white space that may be there. Don't worry about the IEnumerable. That is what this Linq returns. It just means you can loop through it with a For Each loop.
Then we can just call the .Average method on the IEnumerable and we are done.
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim lines As String() = File.ReadAllLines("monthlyBills.txt")
Dim decs As IEnumerable(Of Decimal) = From line In lines
Select CDec(line.Trim)
Dim avg As Decimal = decs.Average
lblAvg.Text = avg.ToString("N2")
End Sub
Here is another example that does not use the Linq query and does use .TryParse. If you use a List instead of an array you don't have to know how many items are going to be added in advance. Also you don't need to keep track of the index. You still use the .Average method on the list.
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim lines As String() = File.ReadAllLines("monthlyBills.txt")
Dim decs As New List(Of Decimal)
Dim dec As Decimal
For Each line As String In lines
If Decimal.TryParse(line, dec) Then
decs.Add(dec)
Else
MessageBox.Show(line & " is not a number and is being excluded from calculations.")
End If
Next
Dim avg As Decimal = decs.Average
lblAvg.Text = avg.ToString("N2")
End Sub

VB.NET - Getting a NaN result, can't figure out why

I'm trying to write a simple GPA calculator where the user enters a grade from an item on a combobox (A,B,C,D,F) and the credit hours of the course, and the calculation will output into a textbox. However, I keep getting a NaN result within the textbox and I can't for the life of me understand why. I've only got a bit of programming experience, so I'd appreciate any help!
Public Class Form1
Public points As Double, hours As Integer
Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
Dim gpaPoints As Double
Dim creditHours As Integer
Dim grade As String
If cmbGrades.SelectedIndex < 0 Then
MsgBox("Please select a grade.")
Exit Sub
ElseIf txtHours.Text = "" Then
MsgBox("Please enter credit hours.")
Else
grade = cmbGrades.SelectedItem
creditHours = CInt(txtHours.Text)
gpaPoints = CalcGPA(grade, creditHours)
points += gpaPoints
hours += creditHours
ClearList()
End If
End Sub
Public Sub ClearList()
cmbGrades.SelectedIndex = -1
cmbGrades.Text = "Select a grade"
txtHours.Text = ""
End Sub
Public Function CalcGPA(grade As String, creditHours As Integer)
Dim gpaPoints As Double
Select Case (grade)
Case "A"
gpaPoints = 4
Case "B"
gpaPoints = 3
Case "C"
gpaPoints = 2
Case "D"
gpaPoints = 1
Case Else
gpaPoints = 0
End Select
Return gpaPoints
End Function
Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
Dim calcGpa As Double = points / hours
txtGpa.Text = FormatNumber(calcGpa, 2)
End Sub
End Class
I basically have the record button which works fine clearing the list and allows someone to enter a second grade, but the calculate button is not working and I can't figure this out. I sincerely appreciate any help.
As a general rule of thumb, if you are getting 'NaN's you can check for the following :
A calculation with any NaN somewhere will give out a NaN
The 0 / 0 division will give a NaN if it's with floating points number. You have a floating point division, so you can check here if your values are not zero when you do your calculation.
Private Sub btnGpa_Click(sender As Object, e As EventArgs) Handles btnGpa.Click
'Dim calcGpa As Double = points / hours '(**did you assign values here?** if not remove this)
dim answer as double = 0
CalcGPA(cmbGrades.SelectedValue, txtHours.Text )
txtGpa.Text = FormatNumber(answer, 2)
End Sub

Simple calculation in VB.Net

I want to calculate Reynolds Number using VB.NET
This is my code:
Public Class Form1
Dim vis As Integer
Dim Den As Integer
Dim hd As Integer
Dim vl As Integer
Dim re As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
vis = Int(TextBox1.Text)
Den = Int(TextBox2.Text)
hd = Int(TextBox4.Text)
vl = Int(TextBox5.Text)
re = (Den * vl * hd) / vl
TextBox3.Show(re)
End Sub
End Class
See my UI here.
Why I am still getting an error message "too many arguments" ?
There are a few things wrong in the code you posted, firstly the calculation is wrong for Reynolds number. Second, please turn on Option Strict as with your current code it would not compile. Third please use conventional naming conventions it makes it difficult in the long run... There's more but not the point...
Suggested Solution
Variable Declaration Meaning:
d = Diameter of the pipe
v = Velocity of Liquid
u = Viscoscity of the Liquid
p = Density of the Liquid
tot = The Reynolds Number
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim d,v,u,p,tot As Single
If Single.TryParse(TextBox1.Text,d) AndAlso Single.TryParse(TextBox2.Text,v) AndAlso Single.TryParse(TextBox3.Text,u) AndAlso Single.TryParse(TextBox1.Text,p) Then
tot = (d * v * p) / (u * 0.001)
MessageBox.Show(tot.ToString)
'OR
TextBox3.Text = tot.ToString
End If
End Sub
The Int function does not do type conversion. It simply returns the integral portion of a value (14.8 would become 14). To do this conversion, you want to use CInt, if you guarantee that the incoming text really is a number.
Since you are using user supplied values, you might want to use some error correction.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Integer.TryParse(TextBox1.Text, vis) AndAlso _
Integer.TryParse(TextBox2.Text, Den) AndAlso _
Integer.TryParse(TextBox4.Text, hd) AndAlso _
Integer.TryParse(TextBox5.Text, vl) Then
'Do your calculation
Else
'There is some kind of error. Don't do the calculation
End If
End Sub
I'm not going to address whether your formula is correct or not.

multiple inputs in text box not totaling

I got another super basic question, im trying to total the subtotals of every entry in the txtPrice.Text the user enters, and then refresh the other lables with the updated tax, shipping, and grand total. Its not totaling the subTotal, everything else works fine. Whats up with that?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub
Tips
In this line:
sglTotal += sglSub
-Every time you work with a total initialize it to zero before adding a value to it. If not it can leads to undesired result.
-When working with currency is better to use a decimal type instead.
If you want a variable keeps its value declare it shared.
This a little example of how you can use a shared field
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class