使用VB创建披萨应用程序

时间:2016-02-23 20:33:21

标签: vb.net

我正在为披萨店创建一个应用程序。我创建了代码(BELOW),用于在选择和累加订单时计算小计,总计和增值税。您支付的越多,您获得的折扣就越大。但不幸的是,我不知道出现了什么问题,因为它回来了“处理了InvalidCastExpectation”。这是我的代码:

    Dim Total As Double
    Dim TotalProducts As Integer
    Dim Vat As Decimal = 0


    For Each Str As String In ListBox5.Items
        Total = Total + Str <<<<<< ( this section is the problem)

    Next
    TextBox9.Text = FormatCurrency(+Total)
    For Each Str As String In ListBox1.Items
        TotalProducts = TotalProducts + CInt(Str)

    Next
    Total = Total = CDbl(Total)
    TextBox6.Text = Format(Total, "0.00")
    TextBox7.Text = Format(20 / 100 * TextBox7.Text)
    TextBox6.Text = Format(+Total + TextBox7.Text)
    Select Total
        Case Is < 10
            TextBox6.Text = Format(Total, "")
            TextBox8.Text = Format(20 / 100 * TextBox6.Text)
            TextBox6.Text = Format(+Total + TextBox7.Text)
        Case Is < 20
            MessageBox.Show("10% discount awarded")
            Total = (Total - (Total * 10 / 100))
            TextBox6.Text = Format(+Total)
            TextBox6.Text = Format(Total, "")
            TextBox8.Text = Format(20 / 100 * TextBox6.Text)
            TextBox8.Text = Format(+Total + TextBox7.Text)

2 个答案:

答案 0 :(得分:0)

声明   Total = Total + Str

尝试添加一个double值(如15.11),其字符串值可能是ABC123或Null。

至少尝试更改&#34; + Str&#34; to&#34; + CDbl(Str)&#34;,但实际上你应该在添加值之前使用Double.TryParse安全地这样做。

答案 1 :(得分:0)

我重新格式化并清理了代码。您可能会想到几个问题:

你想如何计算折扣总额,12.333或12.338总折扣是多少?

增值税应如何四舍五入?

其他人提到的一个大指针是在使用货币时始终使用十进制数据类型。双值可以在每次运行时使用相同的输入值进行更改,通常这种情况会发生在较小的十进制值,但它仍然存在并且可能会咬你。

Private Sub TotalOrder()

Dim total As Decimal = 0
Dim totalProducts As Integer = 0
Dim totalWithVAT As Decimal = 0
Dim vat As Decimal = 0
Dim bDiscountGiven As Boolean = False

For Each sPrice As String In lbItemTotal.Items 'ListBox5.Items
    If IsNumeric(sPrice) Then
        total += CDec(sPrice)
    End If
Next


For Each sCount As String In lbItemCount.Items 'ListBox1.Items
    If IsNumeric(sCount) Then
        totalProducts += CInt(sCount)
    End If
Next

If total >= 10 Then
    total = Math.Round(total * 0.9D, 2)
    bDiscountGiven = True
End If

txtTotal.Text = FormatCurrency(total) ' TextBox9
vat = Math.Round(total * 0.2D, 2)
totalWithVAT = total + vat

txtVAT.Text = vat.ToString("0.00") 'TextBox7.Text
txtTotalWithVAT.Text = totalWithVAT.ToString("0.00") 'TextBox7.Text

If bDiscountGiven Then
    MessageBox.Show("10% discount awarded")
End If

End Sub