0
        Dim index As Integer
        Dim choice As String
        Dim total As Integer

        total = 0

        index = NumericUpDown1.Value


        Dim arr(4) As Integer
        arr(0) = 10
        arr(1) = 5
        arr(2) = 21
        arr(3) = 33




        If index > 0 Then
            choice = (Combobox1.SelectedItem.ToString + " x " + NumericUpDown1.Value.ToString)
            ListBox1.Items.Add(choice)
            CheckedListBox1.Items.Add(choice)
            total += arr(Combobox1.SelectedIndex) * index
            TotalLabel.Text = total.ToString()


      Else
            MsgBox("error.")

        End If

我可以计算单项选择的总数,但无法累计求和。代码有什么问题?

当前情况: 第1步: 选择arr(0),index = 2 total = 20

第 2 步: 选择 arr(2),索引 = 1 总计 = 21

正确情况: 第1步: 选择arr(0), index = 2 total = 20

第 2 步: 选择 arr(2),索引 = 1 总计 = 41

4

1 回答 1

0

您需要一个全局变量或一个带有公共变量的类。您应该创建一个Transaction类来存储有关交易的数据,并可能创建一个类来Product存储有关产品的数据。你放什么取决于你,但我会从这样的事情开始:

Public Class Transaction
    Private _productsList As List(of Product)
    Private _transationNumber As Integer
    '...more stuff...

    'you'll want to remember what products are in your "cart" for the transaction
    Public Property ProductsList As List(of Product)
        'your get/set accessors
    End Property
    Public Property TransactionNumber As Integer
        'your get/set accessors
    End Property
    Public Property TotalTransactionCost() As Double
        Get 
            'this will sum of the prices of all of the products you have stored in your 
            'list of products for this transaction
            Return _productsList.Sum(product => product.Price)
        End Get
    End Property

    Public Sub New()
        '...constructor stuff
    End Sub
    Public Sub AddProductToTransaction(byval product)
        _productsList.Add(product)
    End Sub

End Class

Public Class Product
    Private _price As Double
    Private _productName As String
    Private _UPC As String

    Public Property Price() As Double
        'your get/set accessors
    End Property
    Public Property ProductName() As String
        'your get/set accessors
    End Property
    Public UPC As String () As String
        'your get/set accessors
    End Property

    Public Sub New()
       'constructor stuff
    End Sub
End Class

这些是帮助您入门的几个类 shell。如果您认真地制作产品,那么这是朝着正确方向迈出的一步。如果您要编写代码,请以正确的方式编写代码。

如果您只是在寻找一个快速而肮脏的解决方案,您可以声明一个全局变量并保持一个运行总和。只是不要忘记在开始新交易之前将其清除。

您需要执行以下操作:

Private TransactionCost As Double在所有方法之外的形式中。

同样,我会推荐第一种处理方式。您至少需要这两个类,并且对于真正的产品,它们肯定会更加充实。

我希望这有助于并回答您的问题。如果是这样,请给我点赞并接受答案。欢迎来到 SO。

于 2012-10-27T08:41:16.090 回答