Retrieve exists consecutive lines value VB.Net - vb.net

I should show if there is a consecutive value of lines, if the line contains consecutive values. when it contains at least 2, to display something, when it does not contain, to display something else.
Like my Textbox:
Textbox1.Text = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
For x As Integer = 1 To 4
Next
if I have
2
4
4
10
22
can i somehow show if there are consecutive lines?
MsgBox("Exist")
Else
2
4
22
25
MsgBox("Not Exists")

TextBoxes have a `Lines property, which makes it easy to retrieve lines
'Get the lines from the textbox
Dim lines As String() = Textbox1.Lines
If lines.Length >= 2 Then
Dim consecutiveLines As Boolean = False
Dim previousLine As String = lines(0)
For i = 1 To lines.Length - 1
Dim currentLine = lines(i)
If currentLine = previousLine Then
consecutiveLines = True
Exit For
End If
previousLine = currentLine
Next
If consecutiveLines Then
'Display somthing
Else
'Display somthing else
End If
End If
The trick is to start looping at the second line (lines(1)) and to compare it with the previous line. We have to update the previous line at the end of each loop.
We also store the outcome in a Boolean variable consecutiveLines.
Alternatively, we could access two consecutive lines directly:
'Get the lines from the textbox
Dim lines As String() = Textbox1.Lines
If lines.Length >= 2 Then
Dim consecutiveLines As Boolean = False
For i = 1 To lines.Length - 1 'Start at second line
If lines(i) = lines(i - 1) Then
consecutiveLines = True
Exit For
End If
Next
If consecutiveLines Then
'Display somthing
Else
'Display somthing else
End If
End If
This leads to a somewhat shorter code.

Related

Index textboxes value (from two textboxes)

I have the two textboxes:
First:
Textbox1.lines(0) = 50
Textbox1.lines(1) = 65
Textbox1.lines(2) = 41
Textbox1.lines(3) = 27
Textbox1.lines(4) = 6
Textbox1.lines(5) = 6
Second:
Textbox2.lines(0) = 27
Textbox2.lines(1) = 41
Textbox2.lines(2) = 65
Textbox2.lines(3) = 6
Textbox2.lines(4) = 50
Textbox2.lines(5) = 6
in a third textbox I should display the index that contains the values ​​from the first textbox, but in the second.
Textbox3.lines(0) = 4 (50 of the first textbox is on the second line (lines4)
Textbox3.lines(1) = 2 (65 of the first textbox is on the second line (lines2)
Textbox3.lines(2) = 1 (41 of the first textbox is on the second line (lines1)
Textbox3.lines(3) = 0 (27 of the first textbox is on the second line (lines0)
Textbox3.lines(4) = 3 (6 of the first textbox is on the second line (lines4)
Textbox3.lines(5) = 5 (6 of the first textbox is on the second line (lines5)
although it already exists on line 4 (Number 6), we will move next line, because that line has already been considered. or both index can be displayed.
or somehow the line value becomes null (0) so that it is not taken.
Code: it doesn't work properly, unfortunately.
For Each line In TextBox1.Lines
For l As Integer = 1 To TextBox1.Lines.Length - 1
If TextBox2.Lines(l) = line Then
TextBox3.AppendText(l)
End If
Next
Next
This should work :
For Each line In TextBox1.Lines
Dim i As Integer = 0
While (i < TextBox1.Lines.Length)
If TextBox2.Lines(i) = line Then
TextBox3.AppendText(i & Environment.NewLine)
Continue For
End If
i += 1
End While
Next
With Continue For, the code go to the for's next loop.
Or if you want to display all iterations :
For Each line In TextBox1.Lines
Dim i As Integer = 0
While (i < TextBox1.Lines.Length)
If TextBox2.Lines(i) = line Then
TextBox3.AppendText(i & " ")
End If
i += 1
End While
TextBox3.AppendText(Environment.NewLine)
Next
This approach uses a Dictionary with the number as the key, and a Queue of indices as the value.
When we first encounter a number from TextBox1, we build a queue of all indices where the number occurs in TextBox2. Then each time we encounter that number, we dequeue the next available number where it occurred. If there are none left, then we return -1.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim results As New List(Of String)
Dim occurrences As New Dictionary(Of Integer, Queue(Of Integer))
For Each number As String In TextBox1.Lines
If Not occurrences.ContainsKey(number) Then
occurrences.Add(number, New Queue(Of Integer))
For i As Integer = 0 To TextBox2.Lines.Count - 1
If TextBox2.Lines(i) = number Then
occurrences(number).Enqueue(i)
End If
Next
End If
If occurrences(number).Count > 0 Then
results.Add(occurrences(number).Dequeue)
Else
results.Add("-1")
End If
Next
TextBox3.Lines = results.ToArray
End Sub
I managed to do that as well with the help of a list. In order to work, the number of lines must be equal.
Dim valI As New List(Of Integer)
For nIndex As Integer = 0 To Textbox2.Lines.Length -1
For i As Integer = 0 To TextBox1.Lines.Length - 1
If TextBox2.Lines(nIndex) = TextBox1.Lines(i) Then
If valI.Contains(i) Then
Else
valI.Add(i)
End If
End If
Next
Textbox3.AppendText(vbNewline & valI.Item(nIndex))
Next

Finding Sequence of numbers in Text file

Hello I'm having quite some trouble with this task that was given to me.
I need to find a Sequence of 8 consecutive numbers in a Text file and Put that Line into a MsgBox.
So far I've only found
For Each i As Char In fileLocation
If IsNumeric(i) Then
result += i
End If
Next`
MsgBox(result)
But that won't help me I guess
Edit:
an example Line woudl look like this:
! MK 90 GRAD ALU L 10793013 144 63.00 90 1 3745 !
In this case I would need the 10793013 as an output
Edit 2:
this is the code I currently managed to create
Dim objReader As New System.IO.StreamReader(fileLocation)
Do While objReader.Peek() <> -1
concounter = 0
zeileInhalt = objReader.ReadLine()
ListBox1.Items.Add(zeileInhalt)
For Each zeichen As Char In zeileInhalt
If IsNumeric(zeichen) Then
concounter += 1
vorhanden = True
If vorhanden = False Then
ListBox1.Items.Add(zeileInhalt)
End If
ElseIf IsNumeric(zeichen) = False And concounter = 8 Then
concounter = 0
ElseIf IsNumeric(zeichen) = False And concounter < 8 Then
concounter = 0
ListBox1.Items.Remove(zeileInhalt)
ElseIf concounter > 8 Then
concounter = 0
ListBox1.Items.Remove(zeileInhalt)
vorhanden = False
End If
Next
Loop
'For i As Integer = 0 To fileLocation.Length <> -1
objReader.Close()
The counter itself appears to work however for some reason no entries end up in my listbox.
am I missing a case where the entries are getting removed?
PS: I hope you don't mind the german variable names. If you do
zeileInhalt = content of the row
zeichen = character
vorhanden = existing
Here's another approach to try out:
Dim values() As String
Using objReader As New System.IO.StreamReader(fileLocation)
Do While Not objReader.EndOfStream
values = objReader.ReadLine().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
For Each value As String In values
value = value.Trim()
If value.Length = 8 AndAlso value.All(Function(c) Char.IsDigit(c)) Then
ListBox1.Items.Add(value)
Exit For
End If
Next
Loop
End Using
try to introduce a counter to check the consecutivity in your if clause and reset it and result string to zero once it's not numeric!
Dim result As String = ""
Dim conCounter As Integer = 0
For Each i As Char In fileLocation
If Char.IsDigit(i) Then
conCounter = (conCounter + 1)
result = (result + i)
Else
conCounter = 0
If (result.Length < 8) Then
result = ""
End If
End If
Next
MsgBox(result)
for each word in fileLocation
Dim noExp As New Regex("([0-9]{8,11})")
Dim m As Match = noExp.Match(word)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Msgbox(c.value)
next
how about this ?

Throw ID and its information into listview

I got multiline textbox and ListView
textbox contains :
[1000]
name=John
number0=78569987
[1001]
name=Sara
number0=89768980
number1=77897545
TextBox2.Text = TextBox2.Text.Replace("[", "this what i want")
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
Dim FilterText = "this what i want"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
TextBox2.Lines = lines.ToArray
TextBox2.Text = TextBox2.Text.Replace("this what i want", "")
TextBox2.Text = TextBox2.Text.Replace("]", "")
ListBox1.Items.AddRange(TextBox2.Lines)
For Each x As String In ListBox1.Items
Dim II As New ListViewItem
II.Text = x
ListView1.Items.Add(II)
Next
I cant use the same way to insert numbers and names because some ids contain number0 number 1 and some contain only number 0 ,, so how can I insert their numbers ?
Thanks in advance.
Check the below code with comments. You might have to modify slightly to fit the data.
Check this question and it's linked questions for similar thing.
Edit: Note that this only copies from rows in richtextbox to different columns in listview, so it will work for the examples you provided. I hope you can refine this logic to account for specific columns as per the data coming in the richtextbox.
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
'Add 1st row to the listview
ListView1.Items.Add(New ListViewItem())
'Use Counter to determine row#
Dim j As Integer = 0
'Loop through the items
For i As Integer = 0 To lines.Count - 1
'Check if it's 1st item i.e. ID and add as text (i.e. at Index 0)
If lines(i).StartsWith("[") Then
ListView1.Items(j).Text = lines(i).Substring(1, lines(i).Length - 2)
'Check if contains other columns with attributes
ElseIf lines(i).Contains("=") Then
ListView1.Items(j).SubItems.Add(lines(i).Substring(lines(i).IndexOf("=") + 1))
'Check if it's an empty record, and add new row to listview
Else
j = j + 1
ListView1.Items.Add(New ListViewItem())
End If
Next

There's a glitch when adding numerals to a line CSV (VB.NET)

All of the number 6's in column 6 (Item(5)) should be deleted, and the rest of the numbers should be increased by 1. However, when the process is completed, I check the file and the file is unchanged.
Dim liness As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
For Each line As String In liness
Dim item() As String = line.Split(","c)
Do
If item(5) = 6 Then
liness.Remove(line)
Else : Exit Do
End If
Exit Do
Loop
Console.WriteLine("Have you already entered the next school years, year 3's? (y/n)")
Dim year3s As String = Console.ReadLine
If year3s = "Y" Or year3s = "y" Then
For i As Integer = 1 To liness.Count - 1 'this will read to the end of the array list once
If item(5) > 3 And item(5) < 6 Then
item(5) = item(5) + 1
End If
Next
ElseIf year3s = "N" Or year3s = "n" Then
For i As Integer = 1 To liness.Count - 1 'this will read to the end of the array list once
If item(5) > 2 And item(5) < 6 Then
item(5) = item(5) + 1
End If
Next
End If
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", liness)
Exit For
Next
Exit Do
ElseIf enter.Key = ConsoleKey.End Then
Console.Clear()
adminmenu()
End If
You are updating the 'item' array, but not the 'liness' list. When you write the new 'liness' list to the file, any changes you made to the 'item' array are ignored.
Also, you are writing the 'liness' list back to the file for every loop iteration - this has to be wrong - you probably want to do that after the loop.
While I don't condone using the Split() function for parsing CSV data, I'll leave that part alone here in order to highlight other improvements in the code:
Dim minYear As Integer = 2
Console.WriteLine("Have you already entered the next school years, year 3's? (y/n)")
If Console.ReadLine().ToUpper().Trim() = "Y" Then minYear = 3
Dim NewLines = File.ReadLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv").
Select(Function(l) l.Split(","c) ).
Where(Function(l) Integer.Parse(l(5)) <> 6 ).
Select(Function(l)
Dim x As Integer = Integer.Parse(l(5))
If x >= minYear Then x += 1
l(5) = x.ToString()
Return String.Join(",", l)
End Function).ToList()
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", NewLines)

What is causing 'Index was outside the bounds of the array' error?

What is causing 'Index was outside the bounds of the array' error? It can't be my file, defianetly not. Below is my code:
Sub pupiltest()
Dim exitt As String = Console.ReadLine
Do
If IsNumeric(exitt) Then
Exit Do
Else
'error message
End If
Loop
Select Case exitt
Case 1
Case 2
Case 3
End Select
Do
If exitt = 1 Then
pupilmenu()
ElseIf exitt = 3 Then
Exit Do
End If
Loop
Dim score As Integer
Dim word As String
Dim totalscore As Integer = 0
'If DatePart(DateInterval.Weekday, Today) = 5 Then
'Else
' Console.WriteLine("You are only allowed to take the test on Friday unless you missed it")
' pupiltest()
'End If
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Dim stdntfname As String = founditem(3)
Dim stdntsname As String = founditem(4)
Dim stdntyear As String = founditem(5)
Console.Clear()
If founditem IsNot Nothing Then
Do
If stdntyear = founditem(5) And daytoday = founditem(6) Then
Exit Do
ElseIf daytoday <> founditem(6) Then
Console.WriteLine("Sorry you are not allowed to do this test today. Test available on " & item(6).Substring(0, 3) & "/" & item(6).Substring(3, 6) & "/" & item(6).Substring(6, 9))
Threading.Thread.Sleep(2500)
pupiltest()
ElseIf stdntyear <> founditem(5) Then
Console.WriteLine("Year not found, please contact the system analysts")
Threading.Thread.Sleep(2500)
pupiltest()
End If
Loop
End If
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\testtests.csv")
Dim item() As String = line.Split(","c)
Dim mine As String = String.Join(",", item(2), item(3), item(4), item(5), item(6))
For i As Integer = 1 To 10
Console.WriteLine(i.ToString & "." & item(1))
Console.Write("Please enter the word: ")
word = Console.ReadLine
If word = Nothing Or word <> item(0) Then
score += 0
ElseIf word = item(0) Then
score += 2
ElseIf word = mine Then
score += 1
End If
Next
If score > 15 Then
Console.WriteLine("Well done! Your score is" & score & "/20")
ElseIf score > 10 Then
Console.WriteLine("Your score is" & score & "/20")
ElseIf score Then
End If
Next
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdntscores", True)
sw.Write(stdntfname, stdntsname, stdntyear, score, daytoday, item(7))
Try
Catch ex As Exception
MsgBox("Error accessing designated file")
End Try
End Using
End
End Sub
All help is highly appreciated,
You are constantly replacing the foundItem array when you do founditem = item:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.
Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then
Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then
Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array
So when you try to do the following later, it throws the exception.
Dim stdntfname As String = founditem(3) 'index 3 does not exist!
To fix it do the following change:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
'NOTE: Make sure you know exactly how many columns your csv has or whatever column
' you wish to access.
Dim item() As String = line.Split(","c)
founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
founditem(1) = item(1)
founditem(2) = item(2)
founditem(3) = item(3)
founditem(4) = item(4)
founditem(5) = item(5)
founditem(6) = item(6)
Next
For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet
In your line Dim item() As String = line.Split(","c) there's no guarantee that the correct number of elements exist. It's possible that one of the lines is missing a comma or is a blank trailing line in the document. You might want to add a If item.Length >= 7 and skipping rows that don't have the right number of rows. Also, remember that unlike VB6, arrays in .Net are 0 based not 1 based so make sure that item(6) is the value that you think it is.