Only accept Integer values from InputBox VB.Net within Do While Loop - vb.net

I'm trying to figure out why my program is accepting non-integer values which it then converts to an integer by rounding. The first value the user enters is validated, however, the rest isn't. My program is meant to count the number of odd and even integer numbers the user has entered. Any help would be greatly appreciated.
Private Sub btnShow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddNum.Click
Dim intInputNum As Integer
Dim strInputNum As String = ""
Dim isEven As Integer = 0
Dim isOdd As Integer = 0
Dim userInput As String = InputBox(("Enter a number (0 to end)"))
Dim numArray() As String = strInputNum.Split(New Char() {","c})
Dim validInput As Boolean = Integer.TryParse(userInput, intInputNum)
If validInput = False Then
MsgBox("Invalid input, integer numbers only")
ElseIf validInput = True Then
Do While intInputNum > 0 And validInput = True
If intInputNum Mod 2 = 0 And validInput = True Then
lblEvenValues.Text = lblEvenValues.Text & CStr(intInputNum) & ","
intInputNum = Val(InputBox("Enter a number (0 to end)"))
isEven = isEven + 1
lblCountEven.Text = isEven
ElseIf intInputNum Mod 2 <> 0 And validInput = True Then
lblOddValues.Text = lblOddValues.Text & CStr(intInputNum) & ","
intInputNum = Val(InputBox("Enter a number (0 to end)"))
isOdd = isOdd + 1
lblCountOdd.Text = isOdd
ElseIf validInput = False Then
MsgBox("Invalid input, integer numbers only")
End If
Loop
End If
End Sub

This line:
Do While intInputNum > 0
is causing you issues. When the user inputs a non-integer value, after the first loop, this line: Val(InputBox("Enter a number (0 to end)")) evaluates to zero.
Which is obviously not greater than 0.
Reuse your boolean statement to evaluate userInput, not intInputNum like so:
userInput = Val(InputBox("Enter a number (0 to end)"))
validInput = Integer.TryParse(userInput, intInputNum)
Then you need to fix your message box location to simply show up outside of your loop rather than in it. So when validInput <> True it will break the loop and output your Msgbox.
You will also need to fix your Do While statement to correctly evaluate userInput instead of intInputNum

Related

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 ?

My vowel counter won't count in VB

I need to make a vowel then word counter in vb and it will not work. i have just tried the vowel bit for now but its not working. Any ideas ?
Dim analsyedtext As String
Dim lettercount As Integer
Dim i As Integer
lettercount = 0
Console.WriteLine("Please enter the text to be analysed.")
analsyedtext = Console.ReadLine()
If analsyedtext = "a" Or "e" Or "i" Or "o" Or "u" Then
lettercount = lettercount + 1
End If
Console.Writeline("The number of vowels is,{0}", lettercount)
End Sub
' My preferred function
Private Function VowelCount(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Return (From letter In str.ToLower().ToCharArray()
Where vowels.Contains(letter)
Select letter).Count()
End Function
' This tests all of the functions and Asserts they're identical output
Sub Main()
For Each itm In {"this", "is", "some sort of", "a test that we're doing"}
Dim vowelNum = VowelCount(itm)
Console.WriteLine("{0}: {1}", itm, vowelNum)
Debug.Assert(vowelNum = VowelCount2(itm) AndAlso
vowelNum = VowelCount3(itm) AndAlso
vowelNum = VowelCount4(itm) AndAlso
vowelNum = VowelCount5(itm))
Next
Console.ReadLine()
End Sub
' Identical to above, different syntax
Private Function VowelCount2(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Return str.ToLower().ToCharArray().Where(Function(ltr As Char) vowels.Contains(ltr)).Count()
End Function
' Uses another function IsVowel that does the same thing as vowels.Contains()
Private Function VowelCount3(str As String) As Integer
Dim vowelsInStr As New List(Of Char)
For Each letter As Char In str.ToLower().ToCharArray()
If IsVowel(letter) Then
vowelsInStr.Add(letter)
End If
Next
Return vowelsInStr.Count
End Function
' Different since this doesn't first put vowels into an IEnumerable and then count the vowels, it only does the count
Private Function VowelCount4(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Dim count As Integer
For Each letter In str.ToLower().ToCharArray()
If IsVowel2(letter) Then
count += 1
End If
Next
Return count
End Function
' Same as above but uses a For loop instead of For Each
Private Function VowelCount5(str As String) As Integer
Dim vowels() As Char = "aeiou".ToCharArray()
Dim count As Integer
Dim letters() As Char = str.ToLower().ToCharArray()
For i = 0 To letters.Length - 1
If IsVowel2(letters(i)) Then
count += 1
End If
Next
Return count
End Function
Private Function IsVowel(ltr As Char) As Boolean
Dim vowels() As Char = "aeiou".ToCharArray()
Return vowels.Contains(ltr)
End Function
Private Function IsVowel2(ltr As Char) As Boolean
Dim vowels() As Char = "aeiou".ToCharArray()
For Each vowel As Char In vowels
If vowel = ltr Then
Return True
End If
Next
Return False
End Function
EDIT: Just realized there is more work for you to do, to get each individual letter. But assuming you get to the point where analsyedtext is one letter:
Select Case analsyedtext
Case "a", "e", "i", "o", "u"
lettercount += 1
Case Else
' Do nothing
End Select
What you need to do is examine the input string one character at a time.
You can extract one character at a time by using the SubString function like this (instead of your If..Then..End If piece of code):
For i = 0 To analsyedtext.Length - 1
Dim c = analsyedtext.Substring(i, 1)
If c = "a" OrElse c = "e" OrElse c = "i" OrElse c = "o" OrElse c = "u" Then
lettercount = lettercount + 1
End If
Next
Notice how it starts from zero and goes to analsyedtext.Length - 1 - that is because the first character has an index of zero.

VB.Net InputBox validation negative number

I'm working on a program for a user to input a number in an InputBox. I could write the codes to validate the input value is numeric, but I couldn't came up with a procedure to validate the negative number from InputBox.
Dim UserInput As String = ""
Dim UserInputAsNumber As Integer
Dim SumofTotal As Integer
'to display InputBox
UserInput = (InputBox("Enter a positive number", "Input Needed"))
'to capture userinput is not numeric value
While (Not IsNumeric(UserInput))
UserInput = (InputBox("Enter a positive number", "Input Needed"))
End While
'if userinput is number, convert the value to numeric variable
UserInputAsNumber = CInt(UserInput)
If (UserInputAsNumber <= 0) Then
UserInput = (InputBox("Enter a positive number", "Input Needed"))
Else
SumofTotal = CInt(((UserInputAsNumber * (UserInputAsNumber + 1)) / 2))
'calculation
End If
MessageBox.Show("The sum is " & CStr(SumofTotal))
End Sub
You need to loop through your code until you get a valid positive integer. You can simplify things by using Integer.TryParse to validate the string and convert it to an integer (invalid strings will convert to zero).
Private Sub btnEnterNumbers_Click(sender As Object, e As EventArgs) Handles btnEnterNumbers.Click
Dim UserInput As String = ""
Dim UserInputAsNumber As Integer
Dim SumofTotal As Integer
Do While UserInputAsNumber <= 0
'to display InputBox
UserInput = (InputBox("Enter a positive integer value", "Input Needed", "10"))
'convert to integer, will be zero if not valid integer
Integer.TryParse(UserInput, UserInputAsNumber)
Loop
' Gauss formula to calculate the total of a sequence of numbers from userinput
SumofTotal = CInt(UserInputAsNumber * (UserInputAsNumber + 1) / 2)
MessageBox.Show("The sum of the numbers 1 through " & CStr(UserInputAsNumber) & " is " & CStr(SumofTotal))
End Sub

How do I get an Ascii to warp to a certain value after it has past 122?

I am trying to write an encryption program. The problem I am facing is that I am converting the text to ascii and then adding on the offset. However when it goes past the letter 'z' I want it to warp back to 'a' and go from there.
Sub enc()
Text = TextBox1.Text
finalmessage = ""
letters = Text.ToCharArray
offset = ComboBox1.SelectedItem
For x = LBound(letters) To UBound(letters)
finalmessage = finalmessage + Chr(Asc(letters(x)) + offset)
Next
TextBox2.Text = finalmessage
End Sub
I guess to make it easy to decode afterwards, you should to it somewhat in the line of base64 encoding, first encoding everything to a normalized binary string, then encode in the range you want (since using binary, it has to be something that fits with 2^X).
To match your range, i used a baseset of 32, and a simple encoding decoding example (a bit more verbose that it should be, perhaps)
Module Module1
Dim encodeChars As String = "abcdefghijklmnopqrstuvwxyzABCDEF" ' use 32 as a base
Function Encode(text As String) As String
Dim bitEncoded As String = ""
Dim outputMessage As String = ""
For Each ch As Char In text.ToCharArray()
Dim i As Integer = Convert.ToByte(ch)
bitEncoded &= Convert.ToString(i, 2).PadLeft(8, "0"c)
Next
While bitEncoded.Length Mod 5 <> 0
bitEncoded &= "0"
End While
For position As Integer = 0 To bitEncoded.Length - 1 Step 5
Dim range As String = bitEncoded.Substring(position, 5)
Dim index As Integer = Convert.ToInt32(range, 2)
outputMessage &= encodeChars(index).ToString()
Next
Return outputMessage
End Function
Function Decode(encodedText As String) As String
Dim bitEncoded As String = ""
Dim outputMessage As String = ""
For Each ch In encodedText
Dim index As Integer = encodeChars.IndexOf(ch)
If index < 0 Then
Throw New FormatException("Invalid character in encodedText!")
End If
bitEncoded &= Convert.ToString(index, 2).PadLeft(5, "0"c)
Next
' strip the extra 0's
While bitEncoded.Length Mod 8 <> 0
bitEncoded = bitEncoded.Substring(0, bitEncoded.Length - 1)
End While
For position As Integer = 0 To bitEncoded.Length - 1 Step 8
Dim range As String = bitEncoded.Substring(position, 8)
Dim index As Integer = Convert.ToInt32(range, 2)
outputMessage &= Chr(index).ToString()
Next
Return outputMessage
End Function
Sub Main()
Dim textToEncode As String = "This is a small test, with some special characters! Just testing..."
Dim encodedText As String = Encode(textToEncode)
Dim decodedText As String = Decode(encodedText)
Console.WriteLine(textToEncode)
Console.WriteLine(encodedText)
Console.WriteLine(decodedText)
If Not String.Equals(decodedText, textToEncode) Then
Console.WriteLine("Encoding / decoding failed!")
Else
Console.WriteLine("Encoding / decoding completed succesfully!")
End If
Console.ReadLine()
End Sub
End Module
this then gives the following output?
This is a small test, with some special characters! Just testing...
krugsCzanfzsayjaonwwcBdmebAgkCBufqqhoAlunaqhgBBnmuqhgCdfmnuwcBbamnugcCtbmnAgkCtteeqeuDltoqqhizltoruwCzzofyxa
This is a small test, with some special characters! Just testing...
Encoding / decoding completed succesfully!

VB 2008 (Console) "For Each Loop" Lottery Results Comparison

I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If