VB.net: Error with mid function - vb.net

Im making a program that will only accept a userID which is in a format like Hal456, the first one is in uppercase, next two lowercase and the last three numbers.
I tried going through the program step by step and it fails at the second IF statement.
Sub Main()
Dim userid As String
Dim flag As Boolean
flag = False
Console.WriteLine("Input userID to check format")
userid = "Hal123"
Dim a, b, c, d, e, f As Integer
a = Asc("a")
b = Asc("z")
c = Asc("A")
d = Asc("Z")
e = Asc("0")
f = Asc("9")
If Len(userid) = 6 Then
If Asc(Left(userid, 1)) > c And Asc(Left(userid, 1)) < d Then
If Asc(Mid(userid, 2, 1)) > a And Asc(Mid(userid, 2, 1)) < b Then
If Asc(Mid(userid, 3, 1)) > a And Asc(Mid(userid, 3, 1)) < b Then
If Asc(Mid(userid, 4, 1)) > e And Asc(Mid(userid, 4, 1)) < f Then
If Asc(Mid(userid, 5, 1)) > e And Asc(Mid(userid, 5, 1)) < f Then
If Asc(Mid(userid, 6, 1)) > e And Asc(Mid(userid, 6, 1)) < f Then
flag = True
Console.WriteLine("Format of userID is correct")
End If
End If
End If
End If
End If
End If
End If
If flag = False Then Console.WriteLine("Format is not correct")
Console.ReadLine()
End Sub

I see the problem with the code. It is a simple fix. Just change all the "<" to "<=" and all the ">" to ">=" without quotes.
Reason:
Your Program will not allow "a" and "z" and "0" and "9" to be part of the userid.
Changing it to greater than or equal to solves this.
Hope this helps!

Try this using Regular Expressions:
Sub Main()
Dim userid As String
Dim flag As Boolean
Console.WriteLine("Input userID to check format")
userid = "Hal123"
flag = CheckUserID(userid)
If flag = False Then Console.WriteLine("Format is not correct")
Console.ReadLine()
End Sub
Private Function CheckUserID(userId As String) As Boolean
Dim regex As Regex = New Regex("([A-Z]){1}([a-z]){2}([0-9]){3}")
Dim match As Match = regex.Match(userId)
Return match.Success
End Function

How about using REGEXP for solving this? I think that should be quite straight Forward.
Something like:
string pattern = #"[A-Z][a-z]{2}\d{3}";
Regex rx = new Regex(pattern);
string uid = "";
do
{
Console.WriteLine("Please insert userID:");
uid = Console.ReadLine();
bool check = rx.IsMatch(uid);
} while (!rx.IsMatch(uid));

Related

Im having problems figuring out how to print in an array

Not sure how to output the numbers, once they are in ascending order.
This is the task in the pseudocode that I am trying to move into VB.
Dim a() = {2,3,1,4}
Dim swapped = False
Output the values of a()
Do Swapped 🡨 False
For I = 1 to end of the array Compare a(i-1) with a(i) if they are not in ascending order pass them to swapped (from task 1)
Swapped(a(i-1),a(i)) assign the returned value to the
variable swapped.
While swapped = True
Output the values of a()
Dim num = New Integer() {2, 3, 1, 4}
Dim swapped As Boolean = False
While swapped = False
For i = 1 To 4
If num(i - 1) > num(i) Then
temp = num(i)
num(i) = num(i - 1)
num(i - 1) = temp
swapped = True
Else
swapped = False
End If
Next
End While
While swapped = True
Console.WriteLine(num)
End While
Console.ReadLine()
Here you go:
For Each n As Integer In num
Console.WriteLine(n.ToString)
Next
Btw there's a problem with your swapping algorithm: if they are already in the right you will enter an infinite loop, and if there's a swap on the last number you'll exit the loop even if they are not in the right order. If it puzzles you let me a comment and we'll sort this out.
Although, #laancelot showed you how to output the array, I thought I would show you a simple way to sort an array.
Private Sub OrderArray()
Dim num As Integer() = {2, 3, 1, 4}
Array.Sort(num)
Console.WriteLine("Ascending")
For Each i In num
Console.WriteLine(i.ToString)
Next
'If you want it the other way around
Array.Reverse(num)
Console.WriteLine("Descending")
For Each i In num
Console.WriteLine(i.ToString)
Next
Console.ReadLine()
End Sub
If you don't want to use vb net generic array order method, and you prefer use the swap concept, here you can try:
Private Sub TestOrderSwap()
Dim num = New Integer() {9, 7, 0, 11, 12, 10, 6, 2, 3, 1, 4}
If OrderSwap(num, "ASC") Then
For a = 0 To num.Length - 1
Debug.Print(num(a))
Next
End If
If OrderSwap(num, "DESC") Then
For a = 0 To num.Length - 1
Debug.Print(num(a))
Next
End If
End Sub
Private Function OrderSwap(ByRef myArray As Integer(), OrderType As String) As Boolean
Dim swp As Integer = 0
Dim swpFlg As Boolean = False
For a = 1 To myArray.Length - 1
swp = myArray(a)
For b = 0 To a - 1
If (myArray(b) > swp And OrderType = "ASC") Or (myArray(b) < swp And OrderType = "DESC") Then
For c = a - 1 To b Step -1
myArray(c + 1) = myArray(c)
Next
myArray(b) = swp
swpFlg = True
Exit For
End If
Next
Next
Return swpFlg
End Function

How to fix error "Arithmetic operation resulted in an overflow"

Whenever I want to find out a grade in the program I made.
It highlights the statement k = k + 1 and says:
Arithmetic operation resulted in an overflow
Can someone help?
Sub SearchStudentData()
Dim Sname, G As String
Dim Lname, Lgradetext, position, j, k, position1 As Integer
Dim gradefile As IO.StreamReader
Dim Valid As Boolean
Valid = False
Console.WriteLine("Enter the name of the student of whom you want the grade!")
Sname = Console.ReadLine()
Lname = Len(Sname)
gradefile = New IO.StreamReader("D:\Grades.txt")
Do Until gradefile.EndOfStream
gradetext = gradefile.ReadLine()
Lgradetext = Len(gradetext)
j = 0
k = 0
Do
k = k + 1 'It highlights this line of code
position1 = k
Loop Until Mid(gradetext, k, 1) = ":"
Do
j = j + 1
position = j
Loop Until Mid(Lgradetext, j, 1) = ","
If Sname = Right(gradetext, position1 + 1) And Sname = Left(gradetext, position - 1) Then
Valid = True
End If
If Valid = True Then
G = Right(Lgradetext, Lgradetext - 1)
Console.WriteLine(G)
Else
Valid = False
Console.WriteLine("Ypu have failed this PROGRAM")
End If
Loop
gradefile.Close()
End Sub
Your input is not what you expected. The line from your file has no ":" or "," in it, resulting in an infinite loop, and eventually the error when the counter goes past the max. You could use String.IndexOf() to determine if the value is present, instead of a loop. When the value is not present, -1 will be returned. Here's an example:
Dim indexOfColon As Integer = gradetext.IndexOf(":")
Dim indexOfComma As Integer = gradetext.IndexOf(",")
If indexOfColon <> -1 AndAlso indexOfComma <> -1 Then
' ... both ":" and "," were present in the string, do something with those values ...
End If

VB.net Problem with If-statement not being run when the statement is true

With the following global variables:
Dim SpilleBræt(8, 8) As PictureBox
Dim Position(8, 8) As String
Dim MarkeretFelt(8, 8) As String
Dim FeltFarve As String
Dim x As Integer
Dim y As Integer
Dim AktivMarkering As Boolean = 0
Dim SpilleBrik As String
And this code:
Private Sub PictureBox_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim FeltValg As PictureBox = CType(sender, PictureBox)
If AktivMarkering = 1 Then
x = Mid(sender.name, sender.name.Length - 1, 1)
y = Mid(sender.name, sender.name.Length, 1)
Select Case Position(y, x)
Case "LightTileMarked"
Me.SpilleBræt(y, x).BackgroundImage = My.Resources.ResourceManager.GetObject(SpilleBrik & "LightTile")
Case "DarkTileMarked"
Me.SpilleBræt(y, x).BackgroundImage = My.Resources.ResourceManager.GetObject(SpilleBrik & "DarkTile")
Case Else
'fjerner markerede
Select Case Position(y, x)
Case "BlackTower", "WhiteTower"
MsgBox("TÃ¥rn")
Case "BlackHorse", "WhiteHorse"
MsgBox("Hest")
Case "BlackBishop", "WhiteBishop"
MsgBox("Løber")
Case "WhiteKing", "BlackKing"
MsgBox("Konge")
Case "WhiteQueen", "BlackQueen"
MsgBox("Dronning")
Case "WhitePawn", "BlackPawn"
For k As Integer = y To 1 Step -1
If Position(k, x) = "" Then
If (k + x) Mod 2 = 1 Then
FeltFarve = "DarkTile"
Else
FeltFarve = "LightTile"
End If
Me.SpilleBræt(x, k).BackgroundImage = My.Resources.ResourceManager.GetObject(FeltFarve)
ElseIf Position(k, x) = "WhitePawn" Or Position(k, x) = "BlackPawn" Then
'background død brik
Else
k = 1
End If
Next
End Select
End Select
Else
'indsætter markering
'x,y i picturebox'ens navn fx ->(SpilBrik44) hvor x=4 og y=4
x = Mid(sender.name, sender.name.Length - 1, 1)
y = Mid(sender.name, sender.name.Length, 1)
Select Case Position(y, x)
Case "BlackTower", "WhiteTower"
MsgBox("TÃ¥rn")
Case "BlackHorse", "WhiteHorse"
MsgBox("Hest")
Case "BlackBishop", "WhiteBishop"
MsgBox("Løber")
Case "WhiteKing", "BlackKing"
MsgBox("Konge")
Case "WhiteQueen", "BlackQueen"
MsgBox("Dronning")
Case "WhitePawn", "BlackPawn"
For k As Integer = y To 1 Step -1
If Position(k, x) = "" Then
If (k + x) Mod 2 = 1 Then
FeltFarve = "DarkTileMarked"
Else
FeltFarve = "LightTileMarked"
End If
Me.SpilleBræt(x, k).BackgroundImage = My.Resources.ResourceManager.GetObject(FeltFarve)
MarkeretFelt(x, k) = FeltFarve
AktivMarkering = 1
ElseIf Position(k, x) = "WhitePawn" Or Position(k, x) = "BlackPawn" Then
'background død brik
Else
k = 1
End If
Next
End Select
End If
End Sub
I have a problem with the first If statement aktivmarkering=1, goes directly to the 'Else' even though if statements is true.
First time code is run, aktivmarkering is = 0, and therefore it obviously goes to 'Else', but after that one has ben run AktivMarkering is = 1, and first if should be executed. I don't see why not - anyone whos able to help?
Thanks.

Upper Case in VB 6 text box

How to make first letter in upper case while pressing tab or space in vb 6.0 ?
My code is as follows
txtFirstName.Text = UCase$(txtFirstName.Text)
but it doesn't change after tab or space
It's just simple just do this in the text box keypress events...
Private sub textbox_keypress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub
Use the LostFocus event
Private Sub yourTextBox_LostFocus()
With yourTextBox
'first letter in upper case, the rest, untouched.
.Text = UCase(Mid(.Text, 1, 1)) & Mid(.Text, 2, Len(.Text))
End With
End Sub
Apply the same logic to the KeyDown event and check if the pressed key is the space key.
Private Sub yourTextBox_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 32 Then
With yourTextBox
'first letter in upper case, the rest, untouched.
.Text = UCase(Mid(.Text, 1, 1)) & Mid(.Text, 2, Len(.Text))
.SelStart = Len(.Text) 'put the cursor at the end of the textbox...
End With
End If
End Sub
StrConv Function
Returns a Variant (String) converted as specified.
Syntax
StrConv(string, conversion, LCID)
The StrConv function syntax has these named arguments:
Part Description
string Required. String expression to be converted.
conversion Required. Integer. The sum of values specifying the type of conversion to perform.
LCID Optional. The LocaleID, if different than the system LocaleID. (The system LocaleID is the default.)
Settings
The conversion argument settings are:
Constant Value Description
vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in string to uppercase.
AND THERE IS MORE ...
TO GSERGE
$ means nothing when applied to a function name as opposed to a variable name. VBA uses $ AND B as a suffix to denote similar functionality.
VB6 IS VBA the person who said maybe in VB6 but not in VBA. VB6 program host VBA as their programming language. VB6 on it's own are some app objects and the forms package only - no programming language. It's best to think of VB6 as a VBA host like Office.
If you want to proper case see this WORDBASIC Ver 6 code, (which word 2003 helpfully converted to vba).
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Public Sub MAIN()
Select Case WordBasic.Int(GetModifer)
Case 0
WordBasic.ChangeCase
Case 1
WordBasic.ChangeCase 4
Case 2
WordBasic.ChangeCase 2
Case 3
ProperCase
Case Else
WordBasic.ChangeCase
End Select
End Sub
Private Sub ProperCase()
Dim F
Dim z
Dim a$
Dim P
F = 1
WordBasic.ChangeCase 2
WordBasic.EditBookmark Name:="SerenityChangeCase", SortBy:=0, Add:=1
z = WordBasic.GetSelEndPos()
WordBasic.CharLeft 1
While WordBasic.GetSelEndPos() < z And Not WordBasic.AtEndOfDocument()
WordBasic.SelectCurWord
a$ = WordBasic.[Selection$]()
P = 0
If LCase(a$) = "a" Then
P = 1
ElseIf LCase(a$) = "an" Then
P = 1
ElseIf LCase(a$) = "as" Then
P = 1
ElseIf LCase(a$) = "at" Then
P = 1
ElseIf LCase(a$) = "be" Then
P = 1
ElseIf LCase(a$) = "by" Then
P = 1
ElseIf LCase(a$) = "in" Then
P = 1
ElseIf LCase(a$) = "is" Then
P = 1
ElseIf LCase(a$) = "of" Then
P = 1
ElseIf LCase(a$) = "on" Then
P = 1
ElseIf LCase(a$) = "or" Then
P = 1
ElseIf LCase(a$) = "to" Then
P = 1
ElseIf LCase(a$) = "and" Then
P = 1
ElseIf LCase(a$) = "are" Then
P = 1
ElseIf LCase(a$) = "for" Then
P = 1
ElseIf LCase(a$) = "the" Then
P = 1
ElseIf LCase(a$) = "from" Then
P = 1
ElseIf LCase(a$) = "what" Then
P = 1
ElseIf LCase(a$) = "with" Then
P = 1
End If
If P = 1 And F = 0 Then WordBasic.Insert LCase(a$)
WordBasic.WordRight 1
F = 0
Wend
WordBasic.WW7_EditGoTo Destination:="SerenityChangeCase"
WordBasic.EditBookmark Name:="SerenityChangeCase", SortBy:=0, Delete:=1
End Sub
Private Function GetModifer()
Dim a
Dim B
Dim c
Dim X
a = GetAsyncKeyState(16)
B = GetAsyncKeyState(17)
c = GetAsyncKeyState(18)
X = 0
If a < 0 Then X = X + 1
If B < 0 Then X = X + 2
If c < 0 Then X = X + 4
GetModifer = X
End Function
OK. Yeah txtFirstName is a good indicator of usage here.. So I'd use (sort of) Title Caps And I'd do it on the Validate event.. So
Private Sub txtFirstName_Validate(Cancel As Boolean)
Dim p As Integer ' i doubt we'll use more than 32K for a name....
Dim mName As String
p = 1
' first off lets trim any leading blanks.. assume NOTHING and make sure its all lower case..
mName = LCase(LTrim(txtFirstName))
Do While p > 0 And p <= Len(txtFirstName) ' start with the first non-blank
Mid(mName, p, 1) = UCase(Mid(mName, p, 1))
p = InStr(p, mName, " ")
If p > 0 And p < Len(mName) Then p = p + 1
Loop
Cancel = False
txtFirstName = mName
End Sub
Works every time, and capitalizes each word.. Didn't add any code to to do TRUE title caps but this is close, and short & easy...

I'm having trouble with my binary to decimal converter

When I put in a binary number it gives me more than one result in messagebox.show.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As String
Dim a, b, c As Long
a = CLng(Val(TxtBoxInput.Text))
s = TxtBoxInput.Text
TxtBoxInput.Clear()
For i = 1 To Len(s) Step 1
b = CLng(Mid(s, i, 1))
c = Len(s) - i
b = CLng(Val(b) * (2 ^ c))
TxtBoxInput.Text = CStr(MessageBox.Show(CStr(Val(TxtBoxInput.Text) + b)))
Next i
End Sub
You would use the MsgBox Method. It is uncertain from your example where the result is that you are wanting to show.
MsgBox("Information Here", MsgBoxStyle.Information, "MyTitle")
Edit based on Comments
Put your MessageBox outside of your loop something like this:
Dim s, temp As String
Dim a, b, c As Long
a = CLng(Val(TxtBoxInput.Text))
s = TxtBoxInput.Text
TxtBoxInput.Clear()
For i = 1 To Len(s) Step 1
b = CLng(Mid(s, i, 1))
c = Len(s) - i
b = CLng(Val(b) * (2 ^ c))
temp = CStr(Val(temp) + b)
Next i
MessageBox.Show(temp)
Dim s As String
Dim a, b, c As Long
a = CLng(Val(TxtBoxInput.Text))
s = TxtBoxInput.Text
TxtBoxInput.Clear()
For i = 1 To Len(s) Step 1
b = CLng(Mid(s, i, 1))
c = Len(s) - i
b = CLng(Val(b) * (2 ^ c))
TxtBoxInput.Text = CStr(Val(TxtBoxInput.Text) + b)
Next i
MSGBOX(TXTBOXINPUT)