How to stop message box repeating because of array? - vb.net

I'm trying to make a hangman game and to input "incorrect" if the user picks the wrong letter but it will keep repeating because of the randomWord which chooses the word from an array how do I stop this?
Sub wordGeneration()
Dim wordUsed As Array = {"pizza", "noodle", "zombie", "object", "rowin", "running", "elephant", "lion"}
Dim random As New Random
randomWord = wordUsed(random.Next(0, 8))
Label2.Text = randomWord
End Sub
Sub letterInput()
For i As Integer = 0 To randomWord.Length - 1
If userInput = randomWord(i) Then
MessageBox.Show("correct")
ElseIf userInput <> randomWord(i) Then
MessageBox.Show("incorrect")
Label4.Text = counter
End If
Next
End Sub

Simpler and faster to let VB do the search for you.
Sub letterInput()
if InStr(randomWord.Length, userInput) > 0
MessageBox.Show("correct")
Else
MessageBox.Show("incorrect")
Label4.Text = counter
End If
End Sub
Note: I am assuming userInput is a single character.

Related

If condition being ignored

I'm currently writing code for a game called Caladont.
The game is about first player saying the word and the next one has to say the word that starts with last two letters of previous word.
The problem comes when I want to check if word contains less than 3 letters or if it's empty.
In the first cycle when list for filling is still empty, everything is fine.
However, after I type for example 5 or more words and type a single letter or leave it empty, it prints two "You've lost!" messages, which means that code from if statement is being ignored since it changes bool variable to false and is supposed to exit the While loop.
I've tried replacing ok = false with Exit While in condition which checks if words contains less than 3 letters and it worked, but I want to understand what is the problem.
The code can also be found here [Caladont game
GitHub](https://github.com/whistleblower91/VB.net/blob/master/Caladont%20game):
Module Module1
Sub Main()
Kaladont()
End Sub
Sub Kaladont()
Const msg As String = "You've lost!"
Dim list As New List(Of String)
Dim word As String
Dim i As Integer
Dim ok As Boolean
ok = True
While ok
Console.Write("Insert word:")
word = Console.ReadLine()
list.Add(word)
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
End If
If list.Count > 1 Then 'Skip checking first word
For i = 0 To list.Count - 2
If word.ToLower = lista(i).ToLower Then
Console.WriteLine(msg)
ok = False
End If
Next
If LastTwo(word) = "ka" Or LastTwo(word)="nt" Then
Console.WriteLine("KALADONT! You won!")
ok = False
End If
If FirstTwo(list.Last) <> LastTwo(list(list.Count - 2)) Then
Console.WriteLine(msg)
ok = False
End If
End If
End While
Check()
End Sub
Function FirstTwo(ByVal s1 As String) As String
Return Left(s1.ToLower, 2)
End Function
Function LastTwo(ByVal s2 As String) As String
Return Right(s2.ToLower, 2)
End Function
Sub Check()
Dim sign As Char
Console.WriteLine("Do you want to start new game? y\n")
sign = Console.ReadLine()
If sign = CChar("y") Then
Console.Clear()
Kaladont()
ElseIf sign = CChar("n") Then
Exit Sub
End If
End Sub
End Module
Any solutions?
Even if you set ok to false, it will still go inside the other loop, you'll need to use Else
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Else If list.Count > 1 Then 'Skip checking first word
An other way would be to exit the while with End while.
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Exit While
End If

Code iterating through whole string in hangman

How can I stop my code from iterating through a whole string stating whether the input from the user matches that of the random string bearing in mind this is for a hangman game, I want the code to just display once if the user's chosen letter is either correct or incorrect rather than displaying up too eight times.
Sub letterInput()
For i As Integer = 0 To randomWord.Length - 1
If userInput = randomWord(i) Then
MessageBox.Show("correct")
ElseIf userInput <> randomWord(i) Then
MessageBox.Show("incorrect")
Label4.Text = counter
Exit for
End If
Next
End Sub
Sub wordGeneration()
Dim wordUsed As Array = {"pizza", "noodle", "zombie", "object", "rowin", "running", "elephant", "lion"}
Dim random As New Random
randomWord = wordUsed(random.Next(0, 9))
Label2.Text = randomWord
End Sub
What I meant in the comments was that you just need to replace your for loop with a simple if/else. String.Contains checks the whole string already, so there is no need to iterate through each letter anymore:
Sub letterInput()
If randomWord.Contains(userInput) Then
MessageBox.Show("correct")
Else
MessageBox.Show("incorrect")
Label4.Text = counter
End If
End Sub

How do I skip searching through a selected listbox item in vb.net?

I have created the code to search through each string within a listbox to get a substring up until the first space (this is the ID) and check whether the typed ID is in use.
I want to edit this code to skip checking the selected item within the listbox.
For Each lstitem As String In Form1.lst_input.Items
Dim num As Integer = 0
For Each ch As Char In lstitem
If Not Char.IsDigit(ch) Then
Exit For
Else : num += 1
End If
Next ch
If lstitem.Substring(0, Val(num)) = txt_id.Text Then
MsgBox("ID is currently in use", MsgBoxStyle.OkOnly, "ID in use")
txt_id.Text = ""
txt_id.Focus()
Exit Sub
End If
I have tried:
For Each lstitem As String In Form1.lst_input.Items(Not Form1.lst_input.SelectedItem)
and
If lstitem Is Form1.lst_input.SelectedItem Then
but neither work.
Can anyone help?
I finially figured it out. I used the following code:
For Each lstitem As String In Form1.lst_input.Items
Dim num As Integer = 0
If Not lstitem = Form1.lst_input.Items(Form1.lst_input.SelectedIndex) Then
For Each ch As Char In lstitem
If Not Char.IsDigit(ch) Then
Exit For
Else : num += 1
End If
Next ch
End If
If lstitem.Substring(0, Val(num)) = txt_id.Text Then
MsgBox("ID is currently in use", MsgBoxStyle.OkOnly, "ID in use")
txt_id.Text = ""
txt_id.Focus()
Exit Sub
End If

How to search in listview

I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
I don't understand your code, but I do understand the question. Below is example code to search all rows and columns of a listview. Search is case insensitive and supports a "find next match" scenario. If a match or partial match is found in any column the row is selected. TextBox1 gets the text to find. FindBtn starts a new search.
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
Instead of looping like that through the ListView, try using a For Each instead:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
This will select every item which has a text match in a subitem.
Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.
This is the easiest way to search in listview and combobox controls in vb net
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if

Extracting Capital Letters on a String during KeyPress

I have two TextBoxes..
I want to extract/duplicate ALL CAPITAL LETTERS to be inputted by the user to another TextBox during an event of KeyPress.
Logic :
Private Sub TextBox1_KeyPress()
'If the Character is a Capital Letter Then
' Copy and Concatenate it to the second TextBox
'End If
End Sub
You can try this:
For i = 0 To TextBox1.Text.Length - 1
Dim c As Char = TextBox1.Text.Chars(i)
If Char.IsUpper(c) Then
TextBox2.AppendText(c)
End If
Next
If you need it as a function:
Private Function ExtractUppers(ByVal txt As TextBox) As String
Dim sExtract As String = ""
For i = 0 To txt.Text.Length - 1
Dim c As Char = txt.Text.Chars(i)
If Char.IsUpper(c) Then
sExtract = sExtract & c
End If
Next
Return sExtract
End Function
And in your button:
TextBox2.Text = ExtractUppers(TextBox1)
It was solved by my friend! :) Thanks for your replies!
Private Sub TextBox1_TextChange()
CapitalLetter = Regex.Replace(TextBox1.Text, "[^A-Z]", String.Empty)
TextBox2.Text = CapitalLetter
End Sub
Maybe you can use this trick:
If letterVar = letterVar.ToUpper() then
TextBox2.Text &= letterVar
End if