我试图创建一个循环,从每个项目的初始数量减去,直到金额小于项目的价格。它还应该显示在金额低于物品价格之前购买的最后一件物品。汽车售价31万美元,戒指售价12,500美元,钻石售价15万美元,巧克力售价51美元。这些项目位于我的计算机上的文件中,以下是它应该是什么样子的示例。
样本输入:
350000
Car
Ring
Diamond
Car
Chocolate
Diamond
样本输出:
Ring
$27, 500 left
出于某种原因,当我减去时,我得到错误的值,但我无法弄清楚为什么。我已经宣布了每个项目的价格,并多次检查以确保它们是正确的,我已经检查了我的代码,但我仍然不知道为什么我得到了错误的输出。
Private Sub btnS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnS.Click
Dim inFile As StreamReader = New StreamReader("serena.txt")
'Declare the varibles
Dim variableName As String
' the current items from the file
Dim amount As Integer
Dim price As Integer
amount = Val(inFile.ReadLine())
Do
'read in the words
variableName = inFile.ReadLine()
'determine each item's price
If variableName = "car" Then price = 310000
If variableName = "ring" Then price = 12500
If variableName = "diamond" Then price = 150000
If amount >= price Then amount = amount - price
Loop Until amount < price
'output the results
Me.lblOutput.Text = variableName & _
vbNewLine & "Serena has " & Format(amount, "currency") & " left"
End Sub
仔细看看我在下面的代码中添加的评论:
Private Sub btnS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnS.Click
Dim fileName As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "serena.txt")
Dim inFile As New StreamReader(fileName)
Dim itemToPurchase As String
Dim lastThingBought As String = "{ Nothing Bought }" ' what if they can't afford anything?
Dim balance As Integer
Dim price As Integer
Dim somethingBought As Boolean
balance = Val(inFile.ReadLine())
Do
somethingBought = False ' we don't know yet if we can purchase the next item
'read in the words
itemToPurchase = inFile.ReadLine().ToLower().Trim() ' make sure it has no spaces and is lowercase to match below
'determine each item's price
Select Case itemToPurchase
Case "car"
price = 310000
Case "ring"
price = 12500
Case "diamond"
price = 150000
Case "chocolate" ' FYI: you were missing chocolate in your code
price = 51
Case Else ' it could happen!
MessageBox.Show(itemToPurchase, "Unknown Item!")
lblOutput.Text = "Error in file"
Exit Sub
End Select
If balance >= price Then
somethingBought = True
balance = balance - price
' we need to store the last thing purchased,
' because "itemToPurchase" gets replaced with the thing you couldn't afford
lastThingBought = itemToPurchase
End If
' Need to check for the end of file being reached...
' ...they may purchase everything in the file and still have money left!
Loop While Not inFile.EndOfStream AndAlso somethingBought
'output the results
Me.lblOutput.Text = lastThingBought &
vbNewLine & "Serena has " & Format(balance, "currency") & " left"
End Sub