When I run the code, get the results and repeat, the previous user input displays right before the new user input. Any idea? - vb.net

Can anyone help steer me into the right direction?
I am trying to separate the string into characters. If the character is lowercase then the program will uppercase it and vice versa.
Module Module1
Sub Main()
Dim Input As String
Dim Output As New Text.StringBuilder()
Dim repeat As String = "Y"
Do While repeat = "Y"
Console.Clear()
Console.WriteLine("Please enter a word or" &
"phrase and I will change upper case to lower case and vice versa")
Input = Console.ReadLine
For Each ch As Char In Input
If Char.IsLower(ch) Then
Output.Append(Char.ToUpper(ch))
ElseIf Char.IsUpper(ch) Then
Output.Append(Char.ToLower(ch))
Else
Output.Append(ch)
End If
Next
Console.WriteLine(Output.ToString())
Console.Write("Lets try another (Y/N) ")
repeat = UCase(Console.ReadLine())
Loop
Console.ReadKey()
End Sub
End Module

Think about what you're doing with Output; you keep appending to it, but never remove the results from the previous loop from it, so it's gonna display it again and again.
So to fix your problem you need to make sure output is emptied before adding new characters to it. I don't really work with stringbuilders but a simple way would be to just do
Output = New Text.StringBuilder()
at the beginning of your loop

Related

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

Visual Basic Replace is not working

I am writing a simple hangman program and I want to replace something in my variable which stores the letters of the word that have been found.
Here is the code:
Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
wordLettersFound, counter and letter are 3 of the variables I am using.
The variable is all underscores before this script, but it does not change! Can anyone help me with this?
P.S.
I do not know what version of VB I am using, visual studio community 2015 just says 'visual basic'.
Replace doesn't modify the string but returns a new string with the replacement so you should assign it to the variable:
wordLettersFound = Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
Another way to do replace,
Dim theLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzAAA"
theLetters = theLetters.Replace("A"c, "#"c)
There is another way to replace a character in a string. Using the Replace function is a bit awkward in your case because, at the start, all the characters are underscores - Replace as you're using it will replace all of them with the found character.
Instead, you can cut up the string to the piece to the left of the desired replacement, add in the replacement character, and add on the rest of the string. That line is the one after the comment "chop foundWord up and put the character in the right place" in this code:
Module Module1
Sub Main()
Dim wordToFind = "alphabet"
' make a string of dashes the same length as the word to find
Dim foundWord = New String("-"c, wordToFind.Length)
While foundWord <> wordToFind
Console.Write("Enter your guess for a letter: ")
Dim guess = Console.ReadLine()
' make sure the user has only entered one character
If guess.Length = 1 Then
' see if the letter is in the string
Dim pos = wordToFind.IndexOf(guess)
While pos >= 0
' chop foundWord up and put the character in the right place
foundWord = foundWord.Substring(0, pos) & guess & foundWord.Substring(pos + 1)
' see if there are any more of the same letter
pos = wordToFind.IndexOf(guess, pos + 1)
End While
' show the user the current progress
Console.WriteLine(foundWord)
Else
Console.WriteLine("Please enter just one letter!")
End If
End While
Console.WriteLine("You did it!")
Console.WriteLine("Press enter to leave the program.")
Console.ReadLine()
End Sub
End Module
N.B. Do not use all that code directly for homework because your teacher will find this. And that goes to anyone else doing homework - you know who you are ;)

Console Application on VB2008 - Integer.TryParse Method Error

I am using Integer.TryParse Method to validate whether user input is a numeric or non-numeric in my program.
1)if the user input is numeric, the program will then proceed and validate that the user input is range from 0 to 9.
2)If the user is enter a non-numeric input, the program will display the message "invalid input" and ask user to start from beginning.
Following is my coding:
Sub Main()
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
Dim index As Integer
Dim number As Integer
Dim reEnter As Boolean = True
Console.WriteLine("Please enter 7 integers: ")
Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
Console.WriteLine()
While reEnter
For index = 0 To 6
Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.
If Integer.TryParse(sevenNumbers(index), number) Then
While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End While
Else
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End If
reEnter = False
Next
End While
End Sub
However, when a user enter a non-numeric input, the program can't continue and shows an error that forced to close.
i tried this
Sub Main()
Dim num As Integer
Console.Write("enter num:")
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
Console.WriteLine("valid. num = " & num)
Else
Console.WriteLine("invalid")
End If
End Sub
it does works and i am wondering which part of my coding is wrong??
Thank for help!!
Your two samples of code are different. In your second attempt, you do this:
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
The above code reads into a variable called input that will be a String (because Console.ReadLine returns a String). Then, you try to parse the string into a number.
However, in your original code, you do this (some lines omitted for clarity):
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
...
sevenNumbers(index) = Console.ReadLine()
In this case, you are reading into a variable that you have explicitly declared to be an Integer. If the user types "abc" then the conversion will fail at this point - you won't even get to the TryParse because you can't complete the innput.
Instead of reading to an integer, you need to read into a String variable and then parse that value into an Integer (as you did in your second code).
You could have spotted this yourself by taking note of the line that the error actually occurs on when debugging: you should note that the program crashes on the ReadLine, not on the TryParse.
Um. This line:
sevenNumbers(index) = Console.ReadLine()
Is storing whatever text has been read into an array of Integers. If it's compiling, then by the time you reach any later code, you're too late to control the conversion. It's already happened.
Maybe sevenNumbers should be String()?
(You really ought to turn on OPTION STRICT and OPTION EXPLICIT - it should find problems like this for you when it compiles the code)

VB.NET For Each New Line

I need help making a function that opens a file and for each new line, make a variable like explode("\n", $var) in PHP. I tried
Dim words As String = GetFileContents(OpenFileDialog1.FileName)
For Each word As String In words
Dim doHash As String = MD5(word)
If String.Equals(doHash, hash.Text) Then
Label2.Text = "derp"
Else
Label2.Text = "lol"
End If
Next
but it makes each letter a new variable.
You want to use System.IO.File.ReadLines(OpenFileDialog1.FileName). That will cause the For Each loop to get each line separately.
Specifically:
For Each word As String In File.ReadLines(OpenFileDialog1.FileName)
Dim doHash As String = MD5(word)
If String.Equals(doHash, hash.Text) Then
Label2.Text = "derp"
Else
Label2.Text = "lol"
End If
Next
I notice that your php example is definitely splitting on newlines, but your loop variable is called word. Does your file have one word per line? Doesn't matter much, but I wanted to double check that you're okay with the loop getting each line, not each word (if there's more than one word per line).

I want to create a dynamic variable in vb6

My code-
For i= 1 to 10
str & i = InputBox("Enter a number")
Next i
The problem is that it does not create the variable and highlights the "&" sign. Please help.
P.S. I dont want to use an array.
Edit (Updated requirement from one of the comments):
I can't use an array because its for a school project and i'm not allowed, and the user can enter as many numbers as he wants to, so..?
As Marco says, you can't have variable variables.
Sounds like you need an array instead:
dim inputs(1 To 10) as Integer
For i= 1 to 10
inputs(i) = InputBox("Enter a number")
Next i
UPDATE: Answering requirements of unknown number of inputs, and absence of arrays:
You can possibly use a collection, as this will take new inputs as you require:
'Create a collection and a temp variable
Dim strs As New Collection
Dim str As String
'Loop until the input is empty
Do
str = InputBox("Enter a number")
If str <> "" Then strs.Add (str)
Loop Until str = ""
'Then later you can do
Dim val As String
For Each val In strs
'Do something with val
Next
You say the user can enter as many numbers as they want. Maybe you don't want a For loop then, rather a Do or While loop that you Exit when the user is done (when they leave the input box blank or type "done" or something).
But also, you probably don't need to store all the numbers at once. Just input the number into a single variable, do whatever processing you need to do with it inside the loop body (e.g., add it to a total), and then reuse the same variable name on the next iteration of the loop.
If you really need to store them all at once, yes, you'd need an array (or a Dictionary or Collection object, but still, they're like arrays).
I want to create a dynamic variable in VB6
This is what you think you want, but it certainly is not what you need.
You might use an array for this:
Dim str(10) As String
Dim i As Integer
For i= 1 to UBound(str)
str(i) = InputBox("Enter a number")
Next i
If there is no upper limit, you could use a collection.
Dim str As New Collection
Do
str.Add InputBox("Enter a number"), CStr(str.Count)
Loop Until str(str.Count) = ""
str.Remove str.Count
I think what the poster is trying to do has been misread. They want to use a single variable but continue to update it with additional user input. A VB string will work nicely for this and appending a vbCrLf would make splitting the string to separate the value easy. This is very similar to Tomalak's sample.
Dim strUserInput As String
Do
strUserInput = InputBox("Enter a number")
Text1.Text = Text1.Text & vbCrLf & strUserInput 'I am displaying the user input but another string can be used here also
Loop While Len(strUserInput) > 0