我正在尝试建立一个循环,该循环不断从每个项目的初始金额中减去,直到金额小于某个项目的价格。还应该显示最后购买的商品,其金额小于商品的价格。汽车的成本为310,000美元,钻戒的成本为12,500美元,钻石的成本为150,000美元,巧克力的成本为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
答案 0 :(得分:0)
仔细查看我放入以下代码中的评论:
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