"Simple" array with formula

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Hi everyone,

I've joined this forum in the hope that I can get some help with part of my code. It's very straightforward but I cannot seem to get the hang of arrays. I'm doing this as part of an electronic engineering course but I'm very new to programming and so my code is flaky...

I have to make a programme for a DVD shop where I enter the following in textboxes: ID Code, Title, Price and Quantity. Depending on the quantity there can be discounts if the DVDs are bought in bulk:

0-4 DVDs = No discount
5-9 DVDs = 12% discount
10-14 DVDs = 17% discount
Over 15 DVDs = 25% discount

The section of code below is supposed to create a dynamic array with 6 columns (textboxes, discounts and subtotals) and display it in a console (for testing). Later I plan to save the array to a .txt file.

Anyway, the array appears in the console but the discounts are wrong so I must have the array programmed incorrectly. Can anyone help me with this???


VB.NET:
  Private Sub Results_Array()


        'Dynamic two-dimensional array initialised as object to show different data types

        Dim Results_Array(0 To 5, 0 To 0) As Object
        ReDim Results_Array(0 To 5, 0 To 0)

        Results_Array(0, 0) = TextBox1.Text
        Results_Array(1, 0) = TextBox2.Text
        Results_Array(2, 0) = TextBox3.Text
        Results_Array(3, 0) = TextBox4.Text

        Dim IDCode As String = CStr(Results_Array(0, 0))
        Dim Title As String = CStr(Results_Array(1, 0))
        Dim Price As Single = CSng(Results_Array(2, 0))
        Dim QTY As Integer = CInt(Results_Array(3, 0))
        Dim Discount As Single = CSng(Results_Array(4, 0))
        Dim Subtotal As Single = CSng(Results_Array(5, 0))

        ReDim Preserve Results_Array(0 To 5, 0 To Results_Array.GetUpperBound(0))


        'Applying percentage discounts to entries

        If QTY >= 5 Then
            Discount = Price * QTY * 0.12

        ElseIf QTY >= 10 Then
            Discount = Price * QTY * 0.17

        ElseIf QTY >= 15 Then
            Discount = Price * QTY * 0.25

        Else : Discount = 0

        End If

        Subtotal = (Price * QTY) - Discount


        'Display Array in Console

        For i = 0 To 5
            For j = 0 To Results_Array.GetUpperBound(0)

                System.Console.Write(Results_Array(i, j) & " ")

            Next j
        Next i

        System.Console.Write(Discount & " ")
        System.Console.Write(Subtotal & vbNewLine)


        'Clear textboxes

        TextBox1.Text = Nothing
        TextBox2.Text = Nothing
        TextBox3.Text = Nothing
        TextBox4.Text = Nothing

    End Sub

Sorry for the long post. I don't use forums very often and hope I haven't broken any rules on the first post.

Take it easy...


Jake
 
Last edited:

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Kulrom,

I assumed an array was the best way to save textbox data in a table. That way, I could expand it and implement formulae within the last two columns. I'd then like to add up the subtotals and display them (along with the table) in a .txt file.

Is there a better way of doing this?


Jake
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Thanks Kulrom. If I used a ListView control could I still have contents as objects, the formulae for discounts in each row and the ability to save them in a .txt file in a grid format?

It it obvious why my array isn't working? I'm sure it's performing the discounts for previous rows instead of the current one. It would be a lot easier to do this on Excel but unfortunately, it must be a stand-alone programme.

I'll post my GUI and full code when I finish work later on.

Thanks again,



Jake
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Hi,

I've attached a jpg of my GUI plus the full code so far.

After clicking "Done" the DVD details are formatted and saved to the array (with the discount and subtotal). I had a quick look at the ListView control and I'd still prefer to use an array as it means I can store the data without seeing it. The console is only to help me test the programme.

VB.NET:
Public Class Form1

    Private Sub Clear_Function(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        'Clears textboxes on button click

        TextBox1.Text = Nothing
        TextBox2.Text = Nothing
        TextBox3.Text = Nothing
        TextBox4.Text = Nothing

    End Sub

    Private Sub Data_Present(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


        'Checks all textbox data is present

        If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Then
            Dim msg = "One or more entries are incomplete - please try again."
            MsgBox(msg, vbCritical, Title:="Details Error")

        Else : Data_Check()

        End If

    End Sub

    Private Sub Data_Check()


        'Checks textbox data for Price and Quantity are numeric

        If Not IsNumeric(TextBox3.Text) Or Not IsNumeric(TextBox4.Text) = True Then
            Dim msg = "Either Price or Quantity are of incorrect format - please try again."
            MsgBox(msg, vbCritical, Title:="Details Error")

        Else : Number_Format()

        End If

    End Sub

    Private Sub Number_Format()


        'Formats Price and Quantity to correct decimal places

        TextBox3.Text = FormatNumber(TextBox3.Text, 2)
        TextBox4.Text = FormatNumber(TextBox4.Text, 0)

        Results_Array()

    End Sub

    Private Sub Results_Array()


        'Dynamic two-dimensional array initialised as object to show different data types

        Dim Results_Array(0 To 5, 0 To 0) As Object
        ReDim Results_Array(0 To 5, 0 To 0)

        Results_Array(0, 0) = TextBox1.Text
        Results_Array(1, 0) = TextBox2.Text
        Results_Array(2, 0) = TextBox3.Text
        Results_Array(3, 0) = TextBox4.Text

        Dim IDCode As String = CStr(Results_Array(0, 0))
        Dim Title As String = CStr(Results_Array(1, 0))
        Dim Price As Single = CSng(Results_Array(2, 0))
        Dim QTY As Integer = CInt(Results_Array(3, 0))
        Dim Discount As Single = CSng(Results_Array(4, 0))
        Dim Subtotal As Single = CSng(Results_Array(5, 0))

        ReDim Preserve Results_Array(0 To 5, 0 To Results_Array.GetUpperBound(0))


        'Applying percentage discounts to entries

        If QTY >= 5 Then
            Discount = Price * QTY * 0.12

        ElseIf QTY >= 10 Then
            Discount = Price * QTY * 0.17

        ElseIf QTY >= 15 Then
            Discount = Price * QTY * 0.25

        Else : Discount = 0

        End If

        Subtotal = (Price * QTY) - Discount


        'Display Array in Console

        For i = 0 To 5
            For j = 0 To Results_Array.GetUpperBound(0)

                System.Console.Write(Results_Array(i, j) & " ")

            Next j
        Next i

        System.Console.Write(Discount & " ")
        System.Console.Write(Subtotal & vbNewLine)


        'Clear textboxes

        TextBox1.Text = Nothing
        TextBox2.Text = Nothing
        TextBox3.Text = Nothing
        TextBox4.Text = Nothing

    End Sub

End Class


I'd really like to know why my discounts are incorrect. For example, 10 or 15 of the same DVD only gives a discount of 12% rather than 17% or 25% respectively. This is shown in the attachment, in the last two columns of the console.

The part I haven't written yet is when the user has entered enough DVDs, they click "Calculate Total" and a message box tells them the subtotal, discount, VAT, Total etc. and saves the array and totals to a .txt file (named as the date and time).

Please can you tell me where I've gone wrong with the array? It just won't give me the right discounts.

Thanks for your help so far,


Jake
 

Attachments

  • DVD Store.JPG
    DVD Store.JPG
    45.2 KB · Views: 51

kulrom

Well-known member
Joined
May 10, 2005
Messages
2,854
Location
Republic of Macedonia
Programming Experience
10+
Dvd Shop Application (Very Basic Demo)

I have attached demo project for you. However it needs to be improved in order to be used commercially. Various validations and stuff, DB programming etc. etc.

Currently it contains only the following code:

VB.NET:
    Private Sub ResetButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResetButton.Click
        ResetFields()
    End Sub

    Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
        AddToCart()
    End Sub

    Private Sub AddToCart()
        Dim Price As Decimal = Decimal.Parse(PriceTextBox.Text)
        Dim Qty As Integer = Integer.Parse(QuantityTextBox.Text)

        Dim Discount As Decimal = 0
        If Qty >= 5 Then Discount = Price * Qty * 0.12
        If Qty >= 10 Then Discount = Price * Qty * 0.17
        If Qty >= 15 Then Discount = Price * Qty * 0.25

        Dim lvitem As ListViewItem = ShoppingCart.Items.Add(ItemIdTextBox.Text.Trim)
        lvitem.SubItems.Add(TitleTextBox.Text.Trim)
        lvitem.SubItems.Add(String.Format("{0:n2}", Price))
        lvitem.SubItems.Add(QuantityTextBox.Text)
        lvitem.SubItems.Add(String.Format("{0:n2}", Discount))
        lvitem.SubItems.Add(String.Format("{0:n2}", Price * Qty - Discount))

        ResetFields() ' get ready the fields for a new entry/item
        CalculateGrandTotal()
    End Sub

    Private Sub ResetFields()
        Me.ItemIdTextBox.Text = String.Empty
        Me.QuantityTextBox.Text = String.Empty
        Me.PriceTextBox.Text = String.Empty
        Me.TitleTextBox.Text = String.Empty
    End Sub

    Private Sub CalculateGrandTotal()
        Dim grandtotal As Decimal = 0
        For Each lvitem As ListViewItem In ShoppingCart.Items
            grandtotal += Decimal.Parse(lvitem.SubItems(5).Text)
        Next
        GrandTotalLabel.Text = String.Format("£{0:n2}", grandtotal)
    End Sub
 

Attachments

  • DvdShop.zip
    222 KB · Views: 18

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Kulrom,

Thank you very much for doing this. Much appreciated! I'll run it in a few hours when I get home. Just out of curiosity, did you find out why my array couldn't work out the discounts properly?

Thanks again,

Jake
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Hello again,

I wasn't really expecting anyone to take it seriously- it's the first bit of code I've ever written... certainly not professional material! ;-)

The part that didn't work was the discounts. If you look at the attachment in the console, you can see that my array has the following columns: ID, Title, Price, Quantity, Discount and Subtotal (from left to right). The bottom two rows have incorrect discounts:

3 dvd3 5.00 10 6 (should be 8.5) 44 (should be 41.5) <-- Quantity is 10 so discount should be 17% not 12%
4 dvd4 5.00 15 9 (should be 18.75) 66 (should be 56.25) <-- Quantity is 15 so discount should be 25% not 12%

I think my array is dimensioned wrong.

Can you help?

Thanks



Jake
 

kulrom

Well-known member
Joined
May 10, 2005
Messages
2,854
Location
Republic of Macedonia
Programming Experience
10+
Just change the if statements to:

VB.NET:
        Discount = 0
        If Qty >= 5 Then Discount = Price * Qty * 12 / 100
        If Qty >= 10 Then Discount = Price * Qty * 17 / 100
        If Qty >= 15 Then Discount = Price * Qty * 25 / 100


Means your code is right just the if statements were not working correctly.
In addition, i would never use a single datatype for representing money and such. Rather use Decimal ;)
 

kulrom

Well-known member
Joined
May 10, 2005
Messages
2,854
Location
Republic of Macedonia
Programming Experience
10+
as is the first if statement is always true if you enter qty > 5 .. you see the point?
It says if Qty is higher or equal to 5... so 10 is higher ... 15 is also higher. etc. To fix that you should consider to check if it higher than 5 but less than 10 e.g.

VB.NET:
If Qty >= 5 AndAlso Qty < 10 Then Discount = Price * Qty * 12 / 100
If Qty >= 10 AndAlso Qty < 15 Then Discount = Price * Qty * 17 / 100
etc. etc.

However as mentioned, using arrays for this type of app is not really recommending. Please check the DEMO i posted previously and let me know if you like it
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Thanks again for all your help Kulrom. Your code worked a treat.

I agree- the listbox method is far more effective in this instance and I'd definitely choose it over an array. Obviously I won't be submitting your code as it's not my creation, but I will probably modify it and use a similar list.

I also changed the format of the percentages in my original code to see if it worked and it did! I don't understand why VB.NET prefers fractions instead of decimals but I know what to use in future.

I'll be using this forum a lot in the future and hope I can help someone out one day!

Thanks again ;-)


Jake
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Kulrom,

I know this thread is getting old now but I need some more help with the programme!

I tried to use the IsNumeric function followed by a msgbox to make sure the Price and Qty textboxes contain numbers only and it didn't like it at all!

VB.NET:
   'Checks textbox data for Price and Quantity are numeric
        If Not IsNumeric(PriceTextBox.Text) Or Not IsNumeric(QuantityTextBox.Text) = True Then
            Dim msg = "Either Price or Quantity are of incorrect format - please try again."
            MsgBox(msg, vbCritical, Title:="Details Error")

        End If

end if

Can you tell me why this doesn't work and if there's a different way to do this?

Thanks,

Jake
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
The best method would be to use a more appropriate control for numeric input; such as the NumericUpDown or even the MaskedTextBox with the proper mask.

At quick glance, your code seems OK. Although it appears you have wrapped this If statement in another If statement, so we can't really know what's going on. Where are you calling this code from? Etc, etc...
I see you're new to forums, so here are a few tips to help you get answers: When something doesn't work, please give the error code if one occurs. Phrases such as "it didn't like it at all" don't give us much to work with. :)
Learn to use the debugger. You can place break points in Visual Studio by clicking in the margin. When you run the code, the debugger will pause at the breakpoints and allow you to view the variables using watches and other tools (such as simply hovering over the variable).

Also, use either:
VB.NET:
If Not IsNumeric(PriceTextBox.Text) Or Not IsNumeric(QuantityTextBox.Text) Then
or
VB.NET:
If Not IsNumeric(PriceTextBox.Text) = True Or Not IsNumeric(QuantityTextBox.Text) = True Then
but don't mix the two different syntaxes; it makes it a little confusing.

Welcome to the forums!
 

erupter

Member
Joined
Jun 29, 2010
Messages
12
Programming Experience
1-3
You have to use a reverse order in the way you list the "elseIF" instructions.
This way, starting from the lower, the first instruction that returns true will get executed every time.
So if you buy 45 dvds and the first if is "if >= 5" this one returns true, gets executed, and then control is returned.
You have to reverse the order of the IFs in order to start from the least likely to be true (highest first) to the most likely to be true (lowest).
In this case it's simple because you have just 3 boundaries, but in case you had more rearranging all the lines would be frustrating.
In more complex cases I would advise to use double boundary IF instructions: IF >= num1 And < num 2 then
 

kulrom

Well-known member
Joined
May 10, 2005
Messages
2,854
Location
Republic of Macedonia
Programming Experience
10+
Kulrom,

I know this thread is getting old now but I need some more help with the programme!

I tried to use the IsNumeric function followed by a msgbox to make sure the Price and Qty textboxes contain numbers only and it didn't like it at all!

VB.NET:
   'Checks textbox data for Price and Quantity are numeric
        If Not IsNumeric(PriceTextBox.Text) Or Not IsNumeric(QuantityTextBox.Text) = True Then
            Dim msg = "Either Price or Quantity are of incorrect format - please try again."
            MsgBox(msg, vbCritical, Title:="Details Error")

        End If

end if

Can you tell me why this doesn't work and if there's a different way to do this?

Thanks,

Jake

Try this:

VB.NET:
       If Decimal.TryParse(PriceTextBox.Text, 0) = False OrElse Integer.TryParse(QuantityTextBox.Text, 0) = False Then
            Dim message As String = "Either Price or Quantity are of incorrect format - please try again."
            MessageBox.Show(message, "Details Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End If
 

d0ctorworm

Member
Joined
Nov 28, 2010
Messages
9
Location
UK
Programming Experience
Beginner
Thanks everyone for all your help with this. The reason it didn't work was a combination of not including an "Else" statement and placing the code in the wrong part of the procedure. We live and learn.

Cheers again
Jake
 
Top Bottom