我正在尝试在VB Studio中将两个变量相乘,但是在尝试执行此操作时出现语法错误。
(Quantity * ItemCost)
在第一个括号上给出了语法错误,删除括号会给我一个错误,即方法参数必须括在括号中。
对不起,如果这是相当模糊或非常明显的,我是一般的编程新手,我正在尽力制作简单的程序。我知道我的代码远不是最有效的,但它是我现在能做的最好的。 我的整个代码如下:
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
(我现在已将ItemCost
值更改为不包含£或。但是我仍然在括号中出现语法错误。
答案 0 :(得分:3)
您的代码存在的问题是您没有将乘法的结果分配给任何变量。有些语言允许(计算一个值并扔掉它),但显然VB.NET没有。它试图让你免于常见的程序员错误。
请改为:
Dim TotalCost As Integer = Quantity * ItemCost
乘法的结果现在将存储在变量TotalCost
中,您可以将其用于所需的任何内容。
当然,您也可以将计算结果存储在其中一个操作数变量中(当然,假设它不是常数)。在这种情况下,从变量的名称判断,它没有多大意义,但有时它是合适的:
ItemCost = Quantity * ItemCost ' probably wrong, but syntactically legal
答案 1 :(得分:0)
您还需要正确声明变量。 项目成本不能是整数。
项目成本应该是双倍或十进制
Dim TotalCost as Decimal = Quantity * ItemCost
答案 2 :(得分:0)
您可以删除txtItemPrice.Text
中的ItemCost = cInt(txtItemPrice.Text)
吗?
在现有代码中替换它:
Quantity = cInt(txtQuantity.Text)
Strings (.text)
这是为了将Integer
转换为Dim Total As Integer = Quantity * ItemCost
计算总成本:
Integer
请注意:
Double
数据类型无法保存十进制的值。请改用server.connection-timeout
。