I'm just learning to code in vb.net and am currently messing around with VB.net console applications. I can't for the life of me figure something out. It's probably been asked before on here, but I can't find anything by searching. I just coded a simple "check if Y or N was entered. If y/n was entered, display 'you have entered y/n'" program, and it works fine the first time. However, after the first entry I can't get the process to repeat. All I get back is blank space. For example, if i enter y, I'll get the corresponding message. however, if after that I enter n I get nothing back.
here's the code:
Module Module1
Sub Main()
Console.Title = "Hello"
Console.WriteLine("Y or N")
Dim line As String
line = Console.ReadLine()
Do Until line = "exit"
If line = "y" Then
Console.WriteLine("you have chosen y")
Console.ReadLine()
ElseIf line = "n" Then
Console.WriteLine("you have chosen n")
Console.ReadLine()
End If
line = ""
Loop
End Sub
End Module
I'm assuming the answer's super simple, but I can't seem to figure it out or fin the answer online.
Thanks for the help.
You have to store the value of Console.ReadLine() in the Line string.
Module Module1
Sub Main()
Console.Title = "Hello"
Console.WriteLine("Y or N")
Dim line As String
line = Console.ReadLine()
Do Until line = "exit"
If line = "y" Then
Console.WriteLine("you have chosen y")
ElseIf line = "n" Then
Console.WriteLine("you have chosen n")
End If
line = Console.ReadLine()
Loop
End Sub
End Module
you need to assign Console.Readline() to line in your Do Loop:
Do Until line = "exit"
If line = "y" Then
Console.WriteLine("you have chosen y")
ElseIf line = "n" Then
Console.WriteLine("you have chosen n")
End If
line = Console.ReadLine()
Loop
This line is your problem:
line = ""
You're reading the console but not assigning that to your variable.
Here's how it should be:
Do Until line = "exit"
If line = "y" Then
Console.WriteLine("you have chosen y")
ElseIf line = "n" Then
Console.WriteLine("you have chosen n")
End If
line = Console.ReadLine()
Loop
You need to re-assign line to whatever the next line read from the console is, like so:
Module Module1
Sub Main()
Console.Title = "Hello"
Console.WriteLine("Y or N")
Dim line As String
line = Console.ReadLine()
Do Until line = "exit"
If line = "y" Then
Console.WriteLine("you have chosen y")
ElseIf line = "n" Then
Console.WriteLine("you have chosen n")
End If
line = Console.ReadLine() ''here
Loop
End Sub
End Module
Inside your loop, you're doing Console.ReadLine() without doing anything with the value, and you're then doing line = "". Your loop is going around infinitely with an empty line, and ignoring the user input.
Remove the two lines Console.ReadLine(), and then replace line = "" with line = Console.ReadLine().
Related
I have a 4 different words (financial, location, course, professor) that can be inputted in a textbox, but each word must be used only once per input in the textbox.
For example, I enter a sentence in the textbox like this: "I have a problem with financial because my family is facing a financial problem" the code below processes this sentence into split text.
What I want to do for validation is to inform the user (maybe through msgbox) something like:
"Error - you must used financial only once in a sentence."
In addition, if course, location and professor used more than once in a sentence should also give a msgbox.
Private Sub CommandButton1_Click()
Call SplitText
End Sub
Sub SplitText()
Dim WArray As Variant
Dim TextString As String
TextString = TextBox1
WArray = Split(TextBox1, " ")
If (TextString = "") Then
MsgBox ("Error: Pls Enter your data")
Else
With Sheets("DatabaseStorage")
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(UBound(WArray) + IIf(LBound(WArray) = 0, 1, 0)) = Application.Transpose(WArray)
End With
MsgBox ("Successfully inserted")
End If
End Sub
Try this:
Private Sub CommandButton1_Click()
Call SplitText
End Sub
Sub SplitText()
Dim sentence As String
Dim mycount As Long
sentence = InputBox("Enter the sentence")
mycount = UBound(Split(sentence, "financial"))
If mycount > 1 then
Msgbox "Error - you must used financial only once in a sentence"
End if
'Here the rest of the code you need
End Sub
Hope it helps.
I'm creating a guess the number game in VB.Net. I've got to the point where I'm asking the player if they would like to play again after they have won. When I try and send them back to the main menu if they select that they would like to play again it just exits out of the program.
Sub MainMenu()
Console.WriteLine("Main Menu")
Console.WriteLine("1) Play Game")
Console.WriteLine("2) Instructions")
Console.WriteLine("3) View Score")
Console.WriteLine("4) Exit")
Console.WriteLine()
End Sub
If UserGuess = CorrectNumber Then
PlayerScore = PlayerScore + 1
Console.WriteLine("...CORRECT!!! You win!")
Console.WriteLine("You took " & NOfGuesses & " guesses!")
Console.WriteLine("Press Enter to Continue")
Console.ReadLine()
Console.Clear()
PlayAgainSub()
End If
Sub PlayAgainSub()
Dim PlayAgain As Char
Console.Clear()
Console.WriteLine("Would you like to play again? (Y/N)")
PlayAgain = Console.ReadLine.ToUpper
If PlayAgain = "Y" Then
MainMenu()
ElseIf PlayAgain = "N" Then
Quit()
Else
Console.WriteLine("Option not valid!")
REM Next line waits for 0.5 seconds so the user has time to see the error message.
Threading.Thread.Sleep(500)
Console.Clear()
PlayAgainSub()
End If
End Sub
This isn't all of the code, just what I considered relevant, if you need the rest of it I will update the post.
set a variable for recursion example
Dim recur As Char
then use Do .. loop while
I want to compare the IF argument to a string array. The user will try to put in a teamname into a textbox, if the user uses a swear word anywhere within that textbox, it will display an error message and clear the textbox. If the user has not sworn, it will register the teamname and carry on with the program (As can be seen in the 2nd IF statement). I have tried to get this code to work for a week now and cannot get it to work.
Private Sub SelectionButtonEnter_Click(sender As Object, e As EventArgs) Handles SelectionButtonEnter.Click
Dim HasSworn As Boolean = False
Dim swears() As String = {"Fuck", "fuck", "Shit", "shit", "Shite", "shite", "Dick", "dick", "Pussy", "pussy", "Piss", "piss", "Vagina", "vagina", "Faggot", "faggot"} 'Declare potential swear words the kids can use
For Each swear As String In swears
If InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
SelectionTextBoxTeamName.Clear() 'Clear the textbox
MessageBox.Show("Remember ... You can be disqualified, raise your hand and Blair will set up the program for you again") 'Let the user know they have entered a swear word and ask them to select another team name
End If
If Not InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
Timer1.Enabled = True 'Enable timer 1 for the learn box
Timer3ForSelection.Enabled = True 'Enable this timer to show the learn button
TeamName = SelectionTextBoxTeamName.Text() 'Once this button has been pressed, store the content of that textbox in a the TeamName string
SelectionLabelTeamName.Text = "Welcome " & SelectionTextBoxTeamName.Text & " Please click 'Learn' in the box below to begin" 'Display the contents of the string along with other text here
SelectionLabelTeamNameTL.Text() = "Team Name: " & TeamName 'Display the contents of the string along with other text here
SelectionTextBoxTeamName.BackColor = Color.Green 'Have the back color of the box set to green
SelectionTextBoxTeamName.Enabled = False 'Do not allow the user/users enter another team name
End If
Next 'A next must be declared in a for each statement
End Sub
Thanks in advance.
I don't think I'd approach it that way; if the user types f**kyou, your code wouldn't catch it. How about this instead:
In your code:
If ContainsBannedWord(SelectionTextBoxTeamName.Text) Then
Msgbox "Hold out your hand, bad person. SlapSlapSlap"
Else
Msgbox "Good boy!"
End if
Function ContainsBannedWord(sInput As String) As Boolean
Dim aBannedWords(1 To 5) As String
Dim x As Long
' Make all the banned words capitalized
aBannedWords(1) = "BANNED1"
aBannedWords(2) = "BANNED2"
aBannedWords(3) = "BANNED3"
aBannedWords(4) = "BANNED4"
aBannedWords(5) = "BANNED5"
For x = LBound(aBannedWords) To UBound(aBannedWords)
If InStr(UCase(sInput), aBannedWords(x)) > 0 Then
ContainsBannedWord = True
Exit Function
End If
Next
ContainsBannedWord = False
End Function
OBJECTIVE:
This is a guessing game. The program is to generate a random number between 1 and 500. The user is to guess the number.
The form should include a START button, a listbox to hold all valid guesses, and a label displaying the answer.
Upon clicking the START button, the user will enter a number in response to an InputBox().
If the user’s guess is invalid (not numeric, not a whole number, out of range), display an appropriate message.
If the guess is valid but is not the correct number (high or low), display an appropriate message.
image high quess dialog boximage low quess dialog box
Every time the user guesses a valid numeric guess within range, add the guess to the listbox on the form. Allow the guesses to be shown in multiple columns in the listbox.
If the user successfully guesses the number, display an appropriate message. Include how many guesses they took. Count only valid (in range, integral) numeric guesses as a guess.
Allow the user to quit the game by entering Quit in response to the input box. If the user gives up, tell them the correct number
Important: Display the random number in a label immediately after generating it so that I (and you) know what the number is while I am (and you are) testing it. You can obviously take it out if you really want to play the game.
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
'Declare Variables
Dim strGuess As String
Dim random As New Random
Dim answer As Integer
'Start with empty Boxes
lstGuesses.Items.Clear()
answer = random.Next(1, 500)
lblAnswer.Text = CStr(answer)
Do
Try
strGuess = InputBox("Enter a numeric integer between 1 and 500. , Enter 'quit' to Quit.", "Guessing Game")
lstGuesses.Items.Add(strGuess)
If strGuess = CStr("quit") Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
Exit Do
End If
If CInt(strGuess) < CInt(1) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) > CInt(500) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) = CInt(answer) Then
MessageBox.Show("Got it! You guessed " & lstGuesses.Items.Add(strGuess) & " times!")
End If
If CInt(strGuess) > CInt(answer) And CInt(strGuess) <= CInt(500) Then
MessageBox.Show("Guess is High")
End If
If CInt(strGuess) < CInt(answer) And CInt(strGuess) >= CInt(1) Then
MessageBox.Show("Guess is Low")
End If
If lstGuesses.Items.Contains("quit") = True Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
End If
Catch ex As InvalidCastException
'Make user guess
MessageBox.Show("Invlid Guess. Enter a numeric integer between 1 and 500!")
End Try
Loop While CInt(strGuess) <> answer
End Sub
MY PROBLEM:
I have been trying everything and this is the best i have made yet. This homework is due in 4 hours so any help will be appreciated.
I am suppose to type the word "quit" to end the game. But also give an error message when something other than letters are typed. Every time I type a letter and press enter, it gives the warning that i set but then it crashes. It is not supposed to crash. It says the crash is from:
Loop While CInt(strGuess) <> answer
and the problem is because of an InvalidCastException and says convertion from string to type integer is not valid. I tried doing TRYPARSE but still the same problem. Can anyone tell me how to let me type the word "quit" into the box so that it quits the game, but doesn't make it crash.
Maybe this is not the best way but i think it will help.
What you need to do is Make a new if statement at the top just after the user entered something in the inputbox.
If IsNumeric(strGuess) Or strGuess = CStr("quit") Then
Else
MessageBox.Show("Only Numbers")
GoTo Line1
End If
And here you check "If IsNumeric(strGuess) Or strGuess = CStr("quit") Then"
if yes do nothing
If No show a msgbox and use a goto "GoTo Line1" "so above your do you add Line1:"
If somebody types something like "a" he will go to line1 "so start the do" and the user needs to enter something new in the inputbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Declare Variables
Dim strGuess As String
Dim random As New Random
Dim answer As Integer
'Start with empty Boxes
lstGuesses.Items.Clear()
answer = random.Next(1, 500)
lblAnswer.Text = CStr(answer)
Line1:
Do
Try
strGuess = InputBox("Enter a numeric integer between 1 and 500. , Enter 'quit' to Quit.", "Guessing Game")
lstGuesses.Items.Add(strGuess)
If IsNumeric(strGuess) Or strGuess = CStr("quit") Then
Else
MessageBox.Show("Only Numbers")
GoTo Line1
End If
If strGuess = CStr("quit") Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
Exit Do
End If
If CInt(strGuess) < CInt(1) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) > CInt(500) Then
MessageBox.Show("Invalid Guess. Enter an Integer Number between 1 and 500!")
End If
If CInt(strGuess) = CInt(answer) Then
MessageBox.Show("Got it! You guessed " & lstGuesses.Items.Add(strGuess) & " times!")
End If
If CInt(strGuess) > CInt(answer) And CInt(strGuess) <= CInt(500) Then
MessageBox.Show("Guess is High")
End If
If CInt(strGuess) < CInt(answer) And CInt(strGuess) >= CInt(1) Then
MessageBox.Show("Guess is Low")
End If
If lstGuesses.Items.Contains("quit") = True Then
MessageBox.Show("The number was " & answer & ". Click Start Game to play again.")
End If
Catch ex As InvalidCastException
'Make user guess
MessageBox.Show("Invlid Guess. Enter a numeric integer between 1 and 500!")
End Try
Loop While CInt(strGuess) <> answer
End Sub
I am building language translator for my tribe. I have about 90% it completed. the only problem i am having is that i want to have msgbox pop up and say "translation not found.", when someone enters a phrase or a word that can't be found in the text file which is read " cat | nish stu yah." I can have it pop up when the translation isn't found, but here is the problem when i type in a word that is found the msgbox pop up as well. I dont know if it has to do with that it is running a do while (true) loop or i am just not coding the translator button correctly. the code is:
Do While (True)
Dim line As String = reader.ReadLine
If line Is Nothing Then
Exit Do
End If
Dim words As String() = line.Split("|")
Dim word As String
For Each word In words
If word = TextBox1.Text Then
TextBox2.Text = words(+1)
Else
MessageBox.Show("Translation is not available")
End If
If "" = TextBox1.Text Then
MessageBox.Show("No entry was made.")
End If
Next
Loop
Assuming your file format is:
cat | nish stu yah
with the spaces around the | character, your issue is probably that String.Split will not remove the spaces, so in this case you will end up with:
words(0) = "cat "
words(1) = " nish stu yah"
So, if TextBox1.Text is "cat", it will not match. You could change the comparison to something like this, to make it more forgiving:
If word.Trim().ToLower() = TextBox1.Text.Trim().ToLower() Then
However, you don't really need to loop through words, since you only want to compare the user input against the untranslated version. You are also showing the message box for each line in the translation file. I think you probably want something like this (completely untested):
If "" = TextBox1.Text Then
MessageBox.Show("No entry was made.")
Exit Sub
End If
Dim found As Boolean = False
Do While (True)
Dim line As String = reader.ReadLine()
If line Is Nothing Then
Exit Do
End If
Dim words As String() = line.Split("|"c)
If words(0).Trim().ToLower() = TextBox1.Text.Trim().ToLower() Then
TextBox2.Text = words(1)
found = True
Exit Do
End If
Loop
If Not found Then
MessageBox.Show("Translation is not available")
End If
Still not the most elegant code, but hopefully points you in the right direction.