Storing string then displaying it with a label box - vb.net

I am trying to store the string from an input box and then display it with dashes in the lblbox for a hangman game for a class.
These are the tasks that I am struggling with:
edit the program to allow a Secret Word of any length.
the program will allow the ‘guesser’ to guess 2 times the length of the word. As an example, the word ‘code’ will allow 8 total guesses.
As the user guesses at letters contained in the word the program will:
Count the number of attempts the user has completed.
Replace the appropriate dash (-) with the correct letter, if the correct letter has been guessed.
When all the letters have been guessed correctly all the dashes (-) should be replaced with the appropriate letters, and a message box should appear stating “Great Job playing Hangman.!”
If the user is unable to guess the correct word in the amount of guesses allowed; the dashes (-) should be replaced with GAME OVER! and a message box should appear stating “Sorry the correct word was________”
2 bonus points will be awarded for displaying all incorrect letters guess in a 3rd label control.
4 more additional bonus points will be awarded for not allowing, or counting a user who guesses the same incorrect letter twice.
Here is my code:
Dim strSecretWord As String
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer = 10
Dim intNumofGuesses As Integer = 0
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = ""
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a 5 letter word for user to guess:", "Please input secret word.").ToUpper
'displays five dashes for the secret word
lblSecretWord.Text = lblSecretWord.Text & "-----"
'guessing player recieves inputbox to make letter guesses
MessageBox.Show("The length of the word is 5 letters, you will be given 10 guesses", "10 guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets (10) and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For intNumberofGuesses = 1 To 10
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To 4
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playign Hangman!", "Game Over", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
Else
End If
lblNumberOfAttempts.Text = intNumberofGuesses
intNumberOfRemainingGuesses = intNumberOfRemainingGuesses - 1
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""

I added a list box to keep the guessed letters. Other comments and explanations in line.
Public Class Form3
'Move this to a class level variable so it can be seen by
'all the methods in the class
Private strSecretWord As String
Private Sub btnStartGame_Click(sender As Object, e As EventArgs) Handles btnStartGame.Click
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer
Dim intNumofGuesses As Integer = 0
'Display correct number of dashes
Dim numberOfDashes As Integer = strSecretWord.Length
'Create a string with correct number of dashes
'This uses and overload of the String constructor that takes a Char and an integer
'as arguments and returns a string with that character repeated that number
'of times. The lower case c following "-" indicates that - is a Char.
Dim TotalNumofGuesses = numberOfDashes * 2
lblRemainingNumberOfAttempts.Text = TotalNumofGuesses.ToString
intNumberOfRemainingGuesses = TotalNumofGuesses
Dim dashString As String = New String("-"c, numberOfDashes)
'displays the dashes
lblSecretWord.Text = dashString
'guessing player recieves inputbox to make letter guesses
'You can use an Interpolated string to display variables in line surrounded by { }.
'In older versions of VB String.Format() will yield the same result.
MessageBox.Show($"The length of the word is {numberOfDashes} letters, you will be given {TotalNumofGuesses} guesses", $"{TotalNumofGuesses} guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For counter = 1 To TotalNumofGuesses
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'If lstLettersGuessed.Contains(strLetterGuessed) Then
If lbxLettersGuessed.Items.Contains(strLetterGuessed) Then
MessageBox.Show($"{strLetterGuessed} has already been guessed.", "Try Again")
'need to do this so they are not cheated out of a guess
TotalNumofGuesses += 1
Continue For 'Moves to the next iteration of the For
End If
lbxLettersGuessed.Items.Add(strLetterGuessed)
'lstLettersGuessed.Add(strLetterGuessed)
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To numberOfDashes - 1
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playing Hangman!", "Game Over", MessageBoxButtons.OK)
'Do this at start of game, player wants to see final score
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
End If
'This is a shorter way of incrementing a variable
intNumofGuesses += 1
'Can't put an integer into a Text property, it needs a string
lblNumberOfAttempts.Text = intNumofGuesses.ToString
'This is a shorter way of decrementing a variable
intNumberOfRemainingGuesses -= 1
'Can't put an integer into a Text property, it needs a string
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses.ToString
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
'Do this at start of game
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
End Sub
Private Sub btnSetUp_Click(sender As Object, e As EventArgs) Handles btnSetUp.Click
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = "0"
lblRemainingNumberOfAttempts.Text = "0"
lbxLettersGuessed.Items.Clear()
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a word for user to guess:", "Please input secret word.").ToUpper
End Sub
End Class

Related

Why is Visual Basics Console.ReadLine Buggy and can I fix it?

Hey question about a visual basics program, I am using Console.ReadLine into a string but it seems when I get to that part of the program or any part of my console program the keyboard enter key enters twice or something it completly skips a ReadLine and recieves the input.length 0 before I even have a chance to enter a string.
This isnt runable without my full code I dont think but I cant seem to get ReadLine to prompt for a string when it is initially run, it always returns 0 once and then loops normally. Im wondering if that has something to do with my keyboard or keyboard settings for a visual basics program or command line.
I dont think its a keyboard error because when I am entering code into visual basics it works fine and doesnt send two returns. I couldnt get the full code in code blocks.
...
Shared Sub Main()
Dim s As New Space()
Dim Ship As New Ships()
Dim Run As Boolean = True
Dim ChooseName As Boolean = True
Dim ch As Char
Dim PlayerName As String
While Run = True
s.PrintWelcome()
ch = Convert.ToChar(Console.Read())
If ch = "1" Then
While ChooseName = True
Console.WriteLine("Choose a Name Less then 50 Characters: ")
PlayerName = Console.ReadLine()
If PlayerName.Length > 50 Then
Console.WriteLine("Name is to Long!")
ElseIf PlayerName = "Q" Then
Run = False
Exit While
ElseIf PlayerName.Length <= 0 Then
Console.WriteLine("Please Enter a Player name or Q by itself to quit.")
Else
ChooseName = False
Console.WriteLine("PlayerName: " & PlayerName & " PlayerName.Length: {0}", PlayerName.Length)
End If
End While
If Run = True Then
End If
ElseIf ch = "2" Then
ElseIf ch = "3" Then
Run = False
ElseIf ch = "Q" Then
Run = False
Else
s.PrintWelcome()
End If
End While
End Sub
...
I suspect that you really ought to be structuring your code more like this:
Module Module1
Sub Main()
Do
Console.Write("Please select a menu item from 1, 2, 3 or Q to quit: ")
Dim menuSelection = Console.ReadKey()
Dim input As String = Nothing
Console.WriteLine()
Select Case menuSelection.KeyChar
Case "1"c
Console.WriteLine("What did you want to say about 1?")
input = Console.ReadLine()
Case "2"c
Console.WriteLine("What did you want to say about 2?")
input = Console.ReadLine()
Case "3"c
Console.WriteLine("What did you want to say about 3?")
input = Console.ReadLine()
Case "q"c, "Q"c
Exit Do
Case Else
'Do nothing before repeating the prompt.
End Select
If Not String.IsNullOrEmpty(input) Then
Console.WriteLine("You said: " & input)
End If
Loop
End Sub
End Module
The ReadKey call will immediately read the first key entered by the user. Rather than requiring the user to hit Enter after that key, the application writes the line break itself. It then tests the chararacter represented by that key to see if it is a valid menu item. If it is, it does whatever is appropriate for that item, whether that be reading a line of input or quitting. If the key does not represent a valid menu item then it simply loops back to the prompt. Note also that the Char value entered by the user is actually compared to Char literals, the way it should be done, rather than String literals.

Visual Basic Input Validation

I am new to Visual Basic programming. I'm using a multi-line textbox to accept only numerical inputs from the users.
I need to remove any white space before adding it to my listbox. For example like ( 8) becomes 8 when added into the listbox and I shouldn't let the user proceed if there is no input or only whitespace as an input. Thank you in advance :)
For i As Integer = 0 To Val(TxtInput.Lines.Count) - 1
If TxtInput.Lines(i) = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(TxtInput.Lines(i)) Then 'Tests for Numbers
Temp.LbInput.Items.Add(TxtInput.Lines(i))
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
This is the kind of thing linq-to-objects was made for:
Dim result = TxtInput.Lines.
Select(Function(line) line.Trim).
Where(Function(line) Not String.IsNullOrWhitespace(line) AndAlso IsNumeric(line)).
Select(Function(line) Val(line))
You can also do this:
Dim lines = TxtInput.Lines.Select(Function(line) line.Trim)
If lines.Any(Function(line) Not IsNumeric(line)) Then
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Exit Sub
Else
Dim result = lines.Where(Function(line) Not String.IsNullOrWhitespace(line)).
Select(Function(line) Val(line))
'Do more with "result" here
End If
Just store the trimmed line into a variable
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim() '<======================
If line = "" Then 'Ignores newline inputs
'Placeholder Comment
ElseIf IsNumeric(line) Then 'Tests for Numbers
Temp.LbInput.Items.Add(line)
Temp.Show()
Else
MsgBox("Your input must only be in numbers, check for invalid inputs!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
Also, TxtInput.Lines.Count is an Integer already. No need to convert with Val, which, by the way, converts it into a Double.
Note that you can add items of any type to the ListBox, so you could as well convert the line into the desired type. I don't know if you need Integer or Double. Let's assume that you only want integer numbers. then you can change the code to
If TxtInput.Lines.Count = 0 Then
MsgBox("You have not entered anything. Please enter a number!", 1, "Error")
Else
For i As Integer = 0 To TxtInput.Lines.Count - 1
Dim line As String = TxtInput.Lines(i).Trim()
Dim number As Integer
If line = "" Then
MsgBox("Your input is empty. Please enter some numbers!", 1, "Error")
ElseIf Integer.TryParse(line, number) Then 'Tests for Numbers
Temp.LbInput.Items.Add(number)
Temp.Show()
Else
MsgBox("Please enter only valid numbers!", 1, "Error")
Temp.LbInput.Items.Clear()
Return
End If
Next
End If
(Code changed according to your comments.)
If you want doubles, just declare number as Double and convert with Double.TryParse(line, number).

Preventing non-numeric characters and negative numbers from being entered in the inputbox?

I have a problem. I need to prevent non-numeric characters and negative numbers from being entered in the inputbox. At the present moment I can prevent non-numeric characters. How do I prevent negative numbers. Please see my code below:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim h1, h2, h3, h4, h5, h6, h7, homeTotal As Integer
Dim v1, v2, v3, v4, v5, v6, v7, visitorsTotal As Integer
Dim prompt, title, prompt1, title1 As String
Dim dataHome As String
Dim dataVisitor As String
If String.IsNullOrEmpty(lblHome1st.Text) And String.IsNullOrEmpty(lblVisitors1st.Text) Then
prompt = "Enter number of home runs: First inning."
title = "Home Runs, first inning."
dataHome = InputBox(prompt, title)
If IsNumeric(dataHome) = False Then
MessageBox.Show("Please enter only numeric values.", "Important Note", MessageBoxButtons.OK)
Else
h1 = Convert.ToInt32(dataHome)
lblHome1st.Text = h1
prompt1 = "Enter number of visitor runs: First inning."
title1 = "Visitors Runs, first inning."
dataVisitor = InputBox(prompt1, title1)
If IsNumeric(dataVisitor) = False Then
MessageBox.Show("Please enter only numeric values.", "Important Note", MessageBoxButtons.OK)
lblHome1st.Text = ""
lblHomeTotal.Text = ""
lblVisitorsTotal.Text = ""
Else
v1 = Convert.ToInt32(dataVisitor)
lblVisitors1st.Text = v1
'Calculate totals
homeTotal = h1
visitorsTotal = v1
'Display totals
lblHomeTotal.Text = homeTotal
lblVisitorsTotal.Text = visitorsTotal
'Display in the list box
listScoreBoard.Items.Add("Innings" & " Home team " & "Visitors")
listScoreBoard.Items.Add("1" & ControlChars.Tab & h1 & ControlChars.Tab & v1)
End If
End If
E.g.
Dim number As Integer
If Not Integer.TryParse(inputText, number) OrElse number < 0 Then
'Either inputText is not a number or it is a negative number.
End If
or:
Dim number As Integer
If Integer.TryParse(inputText, number) AndAlso number >= 0 Then
'inputText is a non-negative number.
End If
Not only does the TryParse method of types like Integer validate, it also converts if the data is valid. Two birds with one stone.
If you are already on a form, consider having a TextBox. You can limit the input into a TextBox through the use of KeyPress, KeyUp or Keydown.
In this example, you would discard any key press that is either:
- not a digit, or
- not the first "." (or whatever decimal marker you would use).
While a simple example - I will leave the coding as an exercise for yourself.
This is only a few lines of code - the user cannot enter anything wrong, so you have reduced error checking in your other code.

Why do I keep on looping after I've filled in book info and why doesn't it write in to a file?

Basically, it's an OOP task which creates a class called book. In the submain, there'll be a menu for the user to add new books/ view all book titles/ view all book authors and exit. I haven't got into the view all book titles and authors yet because at the moment I'm getting looped back again after I inserted the book's details. Which also prevents writing to a text file that will store previous books.
' Description: Making a menu that lets the user store their books info (like a librarian).
Sub Main()
'making a book using the attributes and methods
Dim title As String = ""
Dim datepublished As Date = #01/01/0001# ' date is in month/day/year
Dim pagenum As Integer = 0
Dim isbn As String = ""
Dim author As String = ""
Dim amountbooks As Integer = 0
Dim newbook As Book = New Book()
Dim choice As String = ""
'Writing and Reading a text file.
'CreateText creates a text file and returns system.io.streamwriter object.
Dim streamwriter As System.IO.StreamWriter
streamwriter = System.IO.File.CreateText("C:\Users\Local_PC\Desktop\Try_oop_book\bookrecords.txt")
'Making a menu for the client
' A While loop for the menu that checks the user's input
While choice <> "1" Or choice <> "2" Or choice <> "3" Or choice <> "4"
Console.Clear()
Console.WriteLine("----------LIBRARY MENU----------")
Console.WriteLine("[ 1 ]" & "Add New Book(s)")
Console.WriteLine("[ 2 ]" & "View all Book Titles")
Console.WriteLine("[ 3 ]" & "View all Authors")
Console.WriteLine("[ 4 ]" & "Exit")
choice = Console.ReadLine()
If choice <> "1" And choice <> "2" And choice <> "3" And choice <> "4" Then
Console.WriteLine("Please type in a valid input next time, press enter to retry again.")
Console.ReadLine()
Else
'Using choice, it goes to check which menu the user typed in.
If choice = "1" Then
'The user has chosen 1 which is to add new book(s) to the menu system.
'Setting the title of the book using mybook.setTitle
Console.WriteLine("How many books do you want to add?")
amountbooks = Console.ReadLine()
Dim bookarr(amountbooks) As Book 'This will initialise after amountbooks has been entered. Prevents from getting invalid index number of 0.
For x = 1 To amountbooks ' This loop will go over how many amount of books the user wants to add in to.
bookarr(x) = New Book()
Console.WriteLine("What is the title of the book?")
title = Console.ReadLine() 'This gives the value to store inside the variable 'title'
newbook.setTitle(title) 'This line will set that 'title' into array bookarr
Console.WriteLine("When is the book published?")
datepublished = Console.ReadLine()
newbook.setDatePublished(datepublished)
Console.WriteLine("How many page numbers are there?")
pagenum = Console.ReadLine()
newbook.setPageNum(pagenum)
Console.WriteLine("What is the ISBN(code) of the book?")
isbn = Console.ReadLine()
newbook.setISBN(isbn)
Console.WriteLine("Who is the author of the book?")
author = Console.ReadLine()
newbook.setAuthor(author)
Next x
End If
End If
End While
streamwriter.WriteLine(newbook)
End Sub
Change the while clause to replace 'Or' with 'AndAlso':
While choice <> "1" AndAlso choice <> "2" AndAlso choice <> "3" AndAlso choice <> "4"
In your current code if choice is 3 (for example) then it is not 1, 2 or 4 and the code will enter the while loop - in other words you have an infinite loop.

For loop for bowling score array

I am trying to create a bowling program that will display the scores given in a multi-line text box. I've manage to get the program giving an output, but when it runs it skips asking for new inputs and just gives 5 0s on seperate lines and nothing else. I'm completely lost, any help is very much appreciated
EDIT: Sorry should have changed errors to reflect the programs changes, it looks like this now. It gives 0's instead of using the value I gave it, but it does ask for each input now.
For gameNumber As Integer = 1 To 5 Step 1
lblEnterScore.Text = "Enter Score for game #" & gameNumber
Dim Testint As Integer ' define an Integer for testing
Try
Testint = CInt(txtScoreInput.Text) ' try to convert whatever they entered to Int
Catch
MessageBox.Show("Entry is not an Integer") ' If you are here then the CInt failed for some reason, send a message
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End Try
If txtScoreInput.Text.Contains(".") Then
MsgBox("Bowling Score must be a whole number.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
If txtScoreInput.Text > MAXIMUM_SCORE Or txtScoreInput.Text < MINIMUM_SCORE Then
MsgBox("Bowling Score must be between 1 and 300.")
txtScoreInput.SelectAll()
txtScoreInput.Focus()
Exit Sub
End If
scoreInput(gameNumber) = CInt(txtScoreInput.Text)
' and store it in the array
' and increment the gamecounter for the next time through the loop
Next
'btnEnterScore.Enabled = False
' place the good score into the multi-line textbox
txtScoreOutputs.Text = gameScore & vbCrLf & txtScoreOutputs.Text
End Sub
If it was me, here's what I would do... Just a suggestion; I also cut out over half of your code and stopped it from throwing exceptions as well... You can put this in a click event or where ever you need it as well. You can modify this as well to take as many as you want from user input as well not just limit them from entering score's. Your user also has the option to get out of that loop when they choose to do so as well, not keeping them inside the loop...
Private ScoreLists As New List(Of Integer) 'Hold your inputted values
Private Const MAXIMUM_SCORE As Integer = 300 'Max score
Private Const MINIMUM_SCORE As Integer = 1 'Min score
Private blnStop As Boolean = False
Try
For gameNumber As Integer = 1 To 5
Dim intScore As Integer = 0
Do Until (intScore >= MINIMUM_SCORE And intScore <= MAXIMUM_SCORE) OrElse blnStop
If Not Integer.TryParse(InputBox("Please enter a score for game # " & gameNumber.ToString), intScore) Then
If MsgBox("Bowling Score must be a whole number. Stop getting scores?.", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
blnStop = True
Exit For
End If
End If
Loop
ScoreLists.Add(intScore)
Next
'Display the results...
For i As Integer = 0 To ScoreLists.Count - 1
txtScoreOutputs.Text &= ScoreLists.Item(i.ToString)
Next
ScoreLists.Clear()
Catch ex As Exception
End Try
Construct your logic like this (pseudo):
Loop
{
AskUserForInput()
ProcessUserInput()
}
The loop part will control how many scores the user is prompted to enter. The AskUserForInput() function will prompt the user to type in a new score, and the ProcessUserInput() function will get the value and store it in an array or print it to the screen, etc.
Your current logic is not waiting for any new user input before trying to add to the scores. You are also getting zeros because you're setting the txtScoreOutputs with gameScore, which doesn't look like it's been set to the user's input.