Results 1 to 23 of 23

Thread: [RESOLVED] Read lines, convert to integer and divide to get an answer from text file. (HELP) VB

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Resolved [RESOLVED] Read lines, convert to integer and divide to get an answer from text file. (HELP) VB

    Name:  askpng.jpg
Views: 843
Size:  24.0 KB

    Above is my logs file. I want to take/read all lines which date is " 19.12.2017 "
    then get the TOTAL_T in each line.

    First line: TOTAL_T:30
    Second line: TOTAL_T:35
    Third line: TOTAL_T:27

    All three TOTAL_T will be added and it will be divided by the line count which is three because there are only
    three lines that have 19.12.2017. Right?

    So, TotalTemperature = (30+35+27)/3 -> (92)/3 = 30.6666666667

    I want my final output will be...

    " Avg. Temperature = 30.66 (In textbox/Label) "

    Any leads or help? Please thank you. VB.Net beginner here. God bless! Happy New Year!

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Welcome to VBForums

    You can read the lines of a file using File.ReadAllLines, the documentation has an example of how to use it: https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx

    If you loop thru the lines you can check each line to see if it ends with the text you want (eg: If s.EndsWith("/19.12.2017") ), and if it does then do some extra work with that line.

    You should use a variable to keep track of how many there are (just add one to it each time), and another variable to store the total amount. To read the amount from each line you can use .SubString


    After all lines have been read you can work out the average and display it.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    So you're saying that it is possible? Please say yes. Thank you.

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Yes it is possible, and I gave you instructions on how to do it (along with a link to an example for part of it).

    Give it a go, and if you get stuck show us what you have come up with, and give us specific details of what you are stuck on (such as which line of code, any error messages, etc).

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Thank you again! Okay. I'll try it now. I'll be back if I encountered problems

  6. #6

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Hi sir. I understand a little in the link. But I used a different way, I think.
    Code:
    Public Function jan2(ByVal TextSearched As String, ByVal Paragraph As String) As Integer
            Dim location As Integer = 0
            Dim occurances As Integer = 0
            Do
                location = TextSearched.IndexOf(Paragraph, location)
                If location <> -1 Then
                    occurances += 1
                    location += Paragraph.Length
                End If
            Loop Until location = -1
            Return occurances
        End Function
    I used this code.

    So if I want to search for things. it becomes like this, and it is successful.
    Code:
    Detail.text = jan2(TextBox1.Text, "01.01.2018")
    Now. I don't have the slightest idea on what to do next. For adding the Total Temperatures. Can I have some help and tip?
    Last edited by si_the_geek; Dec 31st, 2017 at 09:44 AM. Reason: added Code tags

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Please disregard my first comment. Now I used and tried and succeed in the link you've gave me sir.
    Code:
    Public Class Test
        Private Sub Test_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim path As String = "D:\1.txt"
            Dim readText() As String = File.ReadAllLines(path)
            Dim s As String
            For Each s In readText
                If s.EndsWith("02.01.2018") Or s.EndsWith("02.01.2018 Sprinkler_On") Or s.EndsWith("02.01.2018 Light_On") Then
                    MsgBox("Success")
                End If
            Next
        End Sub
    MsgBox Success showed 3 times because there are 3 records in my text file that is equal in my IF-Statement. Hmm. Can i have a tip on what to do on how to store the no. of records?
    Last edited by si_the_geek; Dec 31st, 2017 at 09:44 AM. Reason: added Code tags

  8. #8
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    When you post code please put it inside code tags so it is displayed in a more readable way - either using the Code/VBCode buttons in the post editor screen (or at the top of the Quick Reply box), or by putting them in manually, like this: [code] code here [/code] (I have added them to your posts above)

    Can i have a tip on what to do on how to store the no. of records?
    Use a variable and add one to it (like you did with occurances in post #6), in the same place you show the message.


    Quote Originally Posted by pogiirojen View Post
    Now. I don't have the slightest idea on what to do next. For adding the Total Temperatures. Can I have some help and tip?
    To get each value, my previous hint was: "To read the amount from each line you can use .SubString" (which allows you to read specific characters from a string).

    When you read a value, add it to a variable to keep track of the total.
    Last edited by si_the_geek; Dec 31st, 2017 at 09:50 AM.

  9. #9

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    I'm sorry. I got it. Binggo. I finally stored the number of line. Now for the second step. Sub string. Thank you sir. I'll search for a while. or can i have a tip or some body structure?

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    •TOTAL_T:30 02.01.2018 Light_On
    •TOTAL_T:21 02.01.2018
    •TOTAL_T:19 02.01.2018 Sprinkler_On
    •TOTAL_T:17 02.01.2018 Sprinkler_On

    Code:
    Dim path As String = "D:\1.txt"
            Dim readText() As String = File.ReadAllLines(path)
            Dim s As String
            Dim substring As String
            Dim Lines As Integer = 0
            For Each s In readText
                If s.EndsWith("02.01.2018") Or s.EndsWith("02.01.2018 Sprinkler_On") Or s.EndsWith("02.01.2018 Light_On") Then
                    Lines += 1
                    substring = Integer.Parse(s.Substring(8, 3))
                End If
            Next
            TextBox2.Text = substring
            TextBox1.Text = Lines
    I have successfully retrieve the TOTAL_T amounts. But when I tested it. The textbox only shows the last one, which is 17.
    I really can't understand on how to put the substring on a variable As integer. etc.

  11. #11
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    That's nicely done so far, and I'm impressed at the use of Integer.Parse

    You are close, it is just a matter of altering the variable a bit (so it is an Integer), and adding to it, eg:
    Code:
    Dim path As String = "D:\1.txt"
            Dim readText() As String = File.ReadAllLines(path)
            Dim s As String
            Dim total As Integer
            Dim Lines As Integer = 0
            For Each s In readText
                If s.EndsWith("02.01.2018") Or s.EndsWith("02.01.2018 Sprinkler_On") Or s.EndsWith("02.01.2018 Light_On") Then
                    Lines += 1
                    total += Integer.Parse(s.Substring(8, 3))
                End If
            Next
            TextBox2.Text = total
            TextBox1.Text = Lines
    To then show the average you just need to use the variables total and lines in a slightly different way.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    Happy New Year! Thank you so much for your help Sir @si_the_geek. All is done. How to do I recommend you in this forum? thanks again!

  13. #13
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: Read lines, convert to integer and divide to get an answer from text file. (HELP)

    I'm happy to help, and happy new year to you too


    As you now have it sorted out, could you please do us a little favour, and mark the thread as Resolved?
    (this saves time reading for those of us who like to answer questions, and also helps those who search to find answers)

    You can do it by clicking on "Thread tools" just above the first post in this thread, then "Mark thread resolved". (like various other features of this site, you need JavaScript enabled in your browser for this to work).

    How to do I recommend you in this forum?
    You can click "rate this post" at the bottom of a post to give points to the person who posted it (the total points received are indicated by the green squares under usernames).

  14. #14

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    Btw. Are you still there? I encountered one last problem. Now i mixed up this codes into the system I'm making.

    Code:
     File.ReadAllLines ("D:/1.txt")
    This one is for path right?

    In my system. I import the text file using OpenFileDialog into a textbox1.

    Now I'm getting an error in this code
    Code:
     File.ReadAllLines.(Form1.TextBox1.Text)
    called "Invalid Characters in path"

    How do I use .ReadLine on a Textbox? Thankk you again.

  15. #15
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    It isn't clear what you mean... are you putting the file name into the textbox? If so, it should work (as long as you remove the dot before the bracket).

    If you are loading the contents of the file into the textbox then you can't use File.ReadAllLines to read it (because that opens a file and reads it), but you might be able to do something like this:
    Code:
            Dim readText() As String = Form1.TextBox1.Text.Split(Environment.NewLine)

  16. #16

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    I mean. Instead of using the path as my basis. I used a textbox with OpenFileDialog as my basis in my system. As seen in the picture below. (TextBox1)
    Name:  helphelp.jpg
Views: 343
Size:  26.1 KB


    Code:
     Dim readText() As String = Form1.TextBox1.Text.Split(Environment.NewLine)
                Dim s As String
                Dim Total As Integer
                Dim Lines As Integer = 0
                For Each s In readText
                    If s.EndsWith("02.01.2018") Or s.EndsWith("02.01.2018 Sprinkler_On") Or s.EndsWith("02.01.2018 Light_On") Or s.EndsWith("02.01.2018 Sprinkler_Light_On") Then
                        Lines += 1
                        Total += Integer.Parse(s.Substring(8, 3))
                    End If
                Next
                Label8.Text = (Total) / Lines & "°C"
    Now by trying this code. I got an error on line
    Code:
      Total += Integer.Parse(s.Substring(8, 3))
    called "Input String was not in a correct format"

    I don't know/don't really get what's wrong here. Every line of the code is correct right? Sir? Or Am I missing a point or something?

  17. #17
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,929

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    It seems that whatever is in s.Substring(8, 3) cannot be converted to a number.

    To find out why you'll need to see what it contains, a simple way would be to show it in a message box.

  18. #18

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    TOTAL_T:30 02.01.2018 Light_On
    TOTAL_T:21 02.01.2018
    TOTAL_T:19 02.01.2018 Sprinkler_On
    TOTAL_T:17 02.01.2018 Sprinkler_On

    Code:
     MsgBox(s.Substring(8, 3))
    It shows.

    30
    :21
    :19
    :17

    Why? I counted every digit and its all the same Only the first one gets the correct but the others are not. Please help.

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    Try...

    Code:
    Total += Integer.Parse(Val(s.Trim.Substring(8)))

  20. #20

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    Hello Mr. Paul.

    I used the same structure and just add a single one into it. Thank you and its fine now Happy New Year!

    Code:
     Total += Integer.Parse(Val(s.Trim.Substring(8, 3)))

  21. #21
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,464

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    The important part was Trim
    The Val(s.Trim.Substring(8) part would retrieve the numeric part (the first two characters) from the truncated string

  22. #22

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    17

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    H1:1023 H2:1022 H3:1021 02.01.2018

    H1:700 H2:480 H3:654 02.01.2018

    Above is my logs..

    Code:
     Dim path As String = "D:\tatlo.txt"
            Dim readText() As String = File.ReadAllLines(path)
            Dim s As String
            Dim Total As Integer
            Dim Lines As Integer = 0
            For Each s In readText
                If s.EndsWith("02.01.2018") Or s.EndsWith("02.01.2018 Sprinkler_On") Or s.EndsWith("02.01.2018 Light_On") Or s.EndsWith("02.01.2018 Sprinkler_Light_On") Then
                    Lines += 1
                    Total += (Integer.Parse(Val(s.Trim.Substring(3, 4))) + Integer.Parse(Val(s.Trim.Substring(11, 4))) + Integer.Parse(Val(s.Trim.Substring(19, 4))))
                End If
                TextBox1.Text = Lines
                TextBox2.Text = Total
    
            Next
    So. I'm back! Hello again and thanks for ur help.

    In this problem. I have successfully added the first line of my logs. But I'm having a problem with my second line? What if it became 3-Digits? I cannot add the second line because it isn't aligned with the first line. What do I need to do? Please help.

  23. #23
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: [RESOLVED] Read lines, convert to integer and divide to get an answer from text f

    I'm not as familiar with .Net string parsing as I am with VB6 and earlier string parsing, and you're using a mix of legacy methods and .Net methods, so I'll just continue with a mix.

    If you don't have fixed field sizes and positions, then you'll have to use more sophisticated parsing methods.
    You can't use fixed position and sizes, so you'll have to search for characters that can isolate the portion of the string that comprise the value of the "field", you're interested in.

    There are a number of approaches, but I'll just throw out a quick one that is easy for me to implement.
    It searches for the ":" character to identify the start of the field, and searches for the space character after the ":" position to find the end of the field.
    InStr is a legacy function that treats the first character in a string as Offset 1, rather than 0.

    I decided to create a function that you would pass it the index of the "field" you are interested in, i.e. 1 for the first field, 2 for the second field, 3 for the third field.
    The function will loop the number of times specified to find the first ":", or second ":", etc...
    Once the desired ":" is found, since the function returns a "1 based offset", when we use it in the "0 based offset" method "Substring", it will be pointing to character after the ":".
    The function then uses Instr again, starting at the position of the ":" looking for the next space character.
    Here we subtract one from the position so we "point" to the character in front of the space.
    We've now isolated the first position and last position of the substring we want, so we can convert that to a value and return it.

    A test example of the parser function.
    Code:
    Public Class Form1
        Dim StringArray() As String = {"H1:1023 H2:1022 H3:1021 02.01.2018", "H1:700 H2:480 H3:654 02.01.2018"}
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            Dim total As Integer
            For i As Integer = 0 To 1
                total += SelectField(1, StringArray(i)) + SelectField(2, StringArray(i)) + SelectField(3, StringArray(i))
                Debug.Print(total.ToString)
            Next
        End Sub
    
        Private Function SelectField(Idx As Integer, Input As String) As Integer
            Dim startPos As Integer = 1
            Dim endPos As Integer
            For i As Integer = 1 To Idx
                startPos = InStr(startPos + 1, Input, ":")
            Next
            endPos = InStr(startPos, Input, " ") - 1
            Return CInt(Val(Input.Substring(startPos, endPos - startPos)))
        End Function
    End Class
    p.s. Perhaps someone may feel like provided a "proper" .Net solution, using only .Net methods rather than using some legacy functions, but evidently so far, they've preferred to work with within your approach rather than push .Net methods on you.
    p.p.s Fixed the original function, changed
    startPos = InStr(startPos, Input, ":")
    to
    startPos = InStr(startPos + 1, Input, ":")
    Last edited by passel; Jan 1st, 2018 at 09:15 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width