Вычитание в циклах, связанных с переменными - PullRequest
0 голосов
/ 19 апреля 2019

Я пытаюсь сделать цикл, который продолжает вычитать из первоначальной суммы каждого предмета, пока сумма не станет меньше цены предмета.Предполагается также показать последний купленный предмет до того, как сумма была меньше цены предмета.Автомобили стоят 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

1 Ответ

0 голосов
/ 20 апреля 2019

Внимательно посмотрите на КОММЕНТАРИИ , которые я поместил в код ниже:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...