2013-11-06 3 views
-1

Я делаю программу, которая позволяет пользователям видеть информацию о песнях, воспроизводить отрывок из них и приобретать выбранные.Как сделать ввод и текстовый файл в Visual Basic?

И разрешите пользователям нажать кнопку «Купить», чтобы купить указанную мелодию.

При проверке:

Пользователи не могут оформить, если они не приобрели ни мелодии, однако они могут выйти из программы.

Используйте InputBox, чтобы пользователи могли вводить свою ставку налога с продаж. Поскольку пользователи вводят значение, вы должны выполнить проверку данных на их входе.

Позвольте пользователям отменить процесс проверки, нажав кнопку «Отмена ввода».

Когда отображается окно ввода, текстовое поле должно иметь фокус, а при добавлении неправильного значения налога неправильное значение должно быть очищено, а текстовое поле должно снова сфокусироваться.

Используйте Write/Writeline для создания текстового файла заказа на поставку с именем PurchaseOrder.txt, который включает дату создания файла и подробный список покупок, промежуточного итога, налога и всего.

При нажатии на кнопку «Покупка» выбранной песни и нажмите на кнопку «Check Out», я получаю сообщение об ошибке, что сказать: «Вы не заказали никаких предметов». Обратитесь к подпрограмме cmdCheckOut_Click в коде ниже. Я думаю, именно там я получаю свои ошибки.

Вот код:

Public Structure musicInfo 
    <VBFixedString(30)> Public title As String 
    <VBFixedString(20)> Public artist As String 
    <VBFixedString(20)> Public genre As String 
    <VBFixedString(10)> Public duration As String 
    Public year As Integer 
    Public price As Double 
    <VBFixedString(15)> Public songFileName As String 
End Structure 

Public Const NoOfTunes = 5 
Public songs(NoOfTunes - 1) As musicInfo 

Option Explicit On 
Imports System.IO 
Public Class frmTunes 
Public index As Integer 
Public purchaseCount As Integer 
Public purchasePrice(10) As Decimal 
Public purchaseTitle(10) As String 


Private Sub frmTunes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

    Dim i As Integer 

    FileOpen(1, "music.dat", OpenMode.Random, , , Len(songs(0))) 
    For i = 0 To NoOfTunes - 1 
     FileGet(1, songs(i)) 
    Next 
    FileClose(1) 

    cmdPrevious.Visible = False 

    DisplaySong(0) 
End Sub 

Sub DisplaySong(ByVal i As Int32) 
    lblTitle.Text = songs(i).title 
    lblArtist.Text = songs(i).artist 
    lblGenre.Text = songs(i).genre 
    lblDuration.Text = songs(i).duration 
    lblYear.Text = Convert.ToString(songs(i).year) 
    lblPrice.Text = Convert.ToString(songs(i).price) 
End Sub 

Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click 
    My.Computer.Audio.Stop() 
End Sub 

Private Sub cmdPurchase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPurchase.Click 
    purchaseTitle(purchaseCount) = lblTitle.Text 
    purchasePrice(purchaseCount) = Convert.ToDecimal(lblPrice.Text) 
    purchaseCount = (purchaseCount + 1) 
End Sub 

Private Sub cmdPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrevious.Click 
    index = (index - 1) 
    If (index < 4) Then 
     cmdNext.Visible = True 
    End If 
    If (index = 0) Then 
     cmdPrevious.Visible = False 
    End If 
    DisplaySong(index) 
End Sub 

Private Sub cmdNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNext.Click 
    index = (index + 1) 
    If (index = NoOfTunes - 1) Then 
     cmdNext.Visible = False 
    End If 
    If (index > 0) Then 
     cmdPrevious.Visible = True 
    End If 
    DisplaySong(index) 
End Sub 

Private Sub cmdPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPlay.Click 
    My.Computer.Audio.Play(songs(index).songFileName) 
End Sub 

Private Sub cmdCheckOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCheckOut.Click 
    Dim decimal1 As Decimal 
    Dim decimal3 As Decimal 
    Dim decimal4 As Decimal 
    Dim str1 As String = "" 
    If (Not purchaseCount) Then 
     MsgBox("You have not ordered any items!", MsgBoxStyle.Exclamation, "Order Error") 
    Else 
     Do While ((IsNumeric(str1) Or (Decimal.Compare(decimal3, Decimal.Zero) < 0)) Or (Decimal.Compare(decimal3, (10D)) > 0)) 
      str1 = InputBox("Enter your tax rate as a % between and including 0 - 10:", "Tax Rate", "", -1, -1) 
      If (str1 <> "") Then 
       If (Not IsNumeric(str1)) Then 
        MsgBox("You must enter a numeric tax rate", MsgBoxStyle.Exclamation, "Tax Rate Error") 
       Else 
        Dim dec3 As Decimal = Convert.ToDecimal(str1) 
        If ((Decimal.Compare(decimal3, Decimal.Zero) < 0) Or (Decimal.Compare(decimal3, (10D)) > 0)) Then 
         MsgBox("You must enter a tax rate between and including 0% - 10%", MsgBoxStyle.Exclamation, "Tax Rate Error") 
        End If 
       End If 
      End If 
     Loop 
     Dim StreamWriter As StreamWriter = File.CreateText("PurchaseOrder.txt") 
     StreamWriter.WriteLine("For Purchases dated: " & DateTime.Now.ToLongDateString()) 
     StreamWriter.WriteLine() 
     Dim num2 As Integer = (purchaseCount - 1) 
     Dim num1 As Integer = 0 
     Do While (num1 <= num2) 
      StreamWriter.Write(Strings.FormatCurrency(CType(Me.purchasePrice(num1), Decimal) & "  ")) 
      StreamWriter.WriteLine(Me.purchaseTitle(num1)) 
      Dim dec1 As Decimal = Decimal.Add(Nothing, Me.purchasePrice(num1)) 
      num1 = (num1 + 1) 

     Loop 
     StreamWriter.WriteLine("------") 
     StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal1, Decimal) & " Subtotal")) 
     Dim decimal2 As Decimal = New Decimal(((Convert.ToDouble(decimal3) * 0.01) * Convert.ToDouble(decimal1))) 
     StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal2, Decimal) & " Tax")) 
     StreamWriter.WriteLine("------") 
     Dim dec4 As Decimal = Decimal.Add(decimal1, decimal2) 
     StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal4, Decimal) & " Total")) 
     MsgBox("Purchase Order has been created", MsgBoxStyle.OkOnly) 
     StreamWriter.Close() 
     Me.Close() 
    End If 
End Sub 
End Class 
+0

вместо 'If (не purchaseCount) затем' попробовать' Если purchaseCount = 0 Then ... ' – Plutonix

ответ

5

Not не делать то, что вы думаете, что он делает. В VB.Net Not operator выполняет побитовое инвертирование по небулевому значению. Так что если purchaseCount = 1, то Not purchaseCount = 0xFFFFFFFE = -2, который с конвертированием в True. Только целочисленное значение 0, которое преобразуется в false.

Изменить тест If (Not purchaseCount) для If (purchaseCount = 0)

+0

После этого, что я получаю сообщение об ошибке на этой строке кода: StreamWriter.WriteLine (Strings.FormatCurrency (CType (decimal1, Decimal) & "Subtotal")) – user2943057

+0

Мы должны догадаться, какая ошибка ???? попробуйте этот 'StreamWriter.WriteLine (decimal1.ToString (« C2 ») &« Итого »)' – Plutonix

+0

@ user2943057 - у вас есть скобки в неправильных местах. StreamWriter.WriteLine (Strings.FormatCurrency (CType (decimal1, Decimal)) и «Итого») – shf301

Смежные вопросы