Is there a way to maintain the length of a user entered number, to prevent removal of extra 0's? - vb.net

I'm creating a Diabetes management algorithm, and I'm trying to find a way for the user's entered time blocks to be maintained at 4 digits
I've been searching on google, but all I have been able to find is how to check the length of a variable, which I already know how to do.
Sub timeBlocks()
Dim file As String = "C:\Users\Connor\Documents\Visual Studio 2017\Projects\meterCodeMaybe\TIMEBLOCKS.txt"
Dim blockNum As Integer
Console.WriteLine("Please be sure to enter times as a 24 hour value, rather than 12 hour, otherwise the input will not be handled.")
Console.Write("Please enter the amount of time blocks you require for your day: ")
blockNum = Console.ReadLine()
Dim timeA(blockNum - 1) As Integer
Dim timeB(blockNum - 1) As Integer
Dim sensitivity(blockNum - 1) As Integer
Dim ratio(blockNum - 1) As Integer
For i = 0 To (blockNum - 1)
Console.WriteLine("Please enter the start time of your time block")
timeA(i) = Console.ReadLine()
Console.WriteLine("Please enter the end time of your time block")
timeB(i) = Console.ReadLine()
Console.WriteLine("Please enter the ratio for this time block (Enter the amount of carbs that go into 1 unit of insulin)")
ratio(i) = Console.ReadLine()
Console.WriteLine("Please enter the insulin sensitivity for this time block
(amount of blood glucose (mmol/L) that is reduced by 1 unit of insulin.)")
sensitivity(i) = Console.ReadLine()
FileOpen(1, file, OpenMode.Append)
PrintLine(1, Convert.ToString(timeA(i)) + "-" + Convert.ToString(timeB(i)) + " 1:" + Convert.ToString(ratio(i)) + " Insulin Sensitivity:" + Convert.ToString(sensitivity(i)) + " per mmol/L")
FileClose(1)
Next
End Sub
Basically, I want the user to be able to enter a 4 digit number for their time block, to match a 24 hr time, so if they enter 0000, it is displayed as this, however, it removes all previous 0's and sets it to just 0.

Perhaps pad the number with 4 leading 0's:
Right(String(digits, "0") & timeA(i), 4)
Or as an alternative, store the value as a string so that it can be printed out in its original form.

I have written a Function to get a 24 hours format time from user, I hope it would help:
Public Function Read24HFormatTime() As String
Dim str As String = String.Empty
While True
Dim c As Char = Console.ReadKey(True).KeyChar
If c = vbCr Then Exit While
If c = vbBack Then
If str <> "" Then
str = str.Substring(0, str.Length - 1)
Console.Write(vbBack & " " & vbBack)
End If
ElseIf str.Length < 5 Then
If Char.IsDigit(c) OrElse c = ":" Then
If str.Length = 0 Then
' allow 0, 1 or 2 only
If c = "0" OrElse c = "1" OrElse c = "2" Then
Console.Write(c)
str += c
End If
ElseIf str.Length = 1 Then
If str = "0" Then
'allow 1 to 9
If c <> ":" Then
If CInt(c.ToString) >= 1 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
ElseIf str = "1" Then
'allow 0 to 9
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
ElseIf str = "2" Then
'allow 0 to 4
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 4 Then
Console.Write(c)
str += c
End If
End If
End If
ElseIf str.Length = 2 Then
'allow ":" only
If c = ":" Then
Console.Write(c)
str += c
End If
ElseIf str.Length = 3 Then
If str = "24:" Then
'allow 0 only
If c = "0" Then
Console.Write(c)
str += c
End If
Else
'allow 0 to 5
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 5 Then
Console.Write(c)
str += c
End If
End If
End If
ElseIf str.Length = 4 Then
If str.Substring(0, 3) = "24:" Then
'allow 0 only
If c = "0" Then
Console.Write(c)
str += c
End If
Else
'allow 0 to 9
If c <> ":" Then
If CInt(c.ToString) >= 0 AndAlso CInt(c.ToString) <= 9 Then
Console.Write(c)
str += c
End If
End If
End If
End If
End If
End If
End While
Return str
End Function
The user can only enter time like 23:59 08:15 13:10 and he couldn't enter formats like 35:10 90:00 25:13 10:61
This is a sample code to show you how to use it:
Dim myTime = DateTime.Parse(Read24HFormatTime())
Dim name = "Emplyee"
Console.WriteLine($"{vbCrLf}Hello, {name}, at {myTime:t}")
Console.ReadKey(True)

Related

Visual basics help-Variables in for loop

I'm trying to get the integers of "num3"(input from the user) and squaring each character and eventually see if its a "happy number"=1 or a "unhappy number" includes 4
For example, 19 is happy number 1^2+9^2=82 , 8^2+2^2=68,6^2+8^2=100, 1^2+0+0=1
Sub Main()
Dim number, num2, total As Integer
Dim num3 As String
Console.Write("pick a number:")
number = Console.ReadLine()
num2 = 0
num3 = Convert.ToString(number)
Do Until total = 1 Or num2 = 4
For Each num3 In num3.Substring(0, num3.Length)
For counter = 1 To num3.Length And num3 = num3.Substring(0, num3.Length)
num2 = num3 ^ 2
total = total + num2
Console.WriteLine(total)
Next
num3 = total
Next
Loop
Console.ReadLine()
If total = 1 Then
Console.WriteLine("happy number")
ElseIf num2 = 4 Then
Console.WriteLine(number & "is a unhappy number")
Console.ReadLine()
End If
End Sub
End Module
however i'm stuck whether "num3" replace itself from the for loop
Here, I believe this should work:
Dim InputNum As Integer = 45 'Your input number
Dim TempNum As Integer = InputNum 'Here we hold number temporarily during steps 19>82....
Do
Dim SumTotal As Double = 0 'sum of numbers squares
For Each number As Char In TempNum.ToString
SumTotal += Integer.Parse(number) ^ 2
Next
TempNum = CInt(SumTotal)
Debug.Print(TempNum.ToString)
'If result is 4 it will loop forever
If SumTotal = 4 Then
Console.WriteLine(InputNum & " is an unhappy number")
Exit Do
ElseIf SumTotal = 1 Then
Console.WriteLine(InputNum & " is a happy number")
Exit Do
End If
Loop

VB.NET textbox remove last dash

How can I remove the last - added after the code has been entered.
All the - are automatically added.
Here my code :
Dim strKeyTextField As String = txtAntivirusCode.Text
Dim n As Integer = 5
Dim intlength As Integer = txtAntivirusCode.TextLength
While intlength > 4
If txtAntivirusCode.Text.Length = 5 Then
strKeyTextField = strKeyTextField.Insert(5, "-")
End If
Dim singleChar As Char
singleChar = strKeyTextField.Chars(n)
While (n + 5) < intlength
If singleChar = "-" Then
n = n + 6
If n = intlength Then
strKeyTextField = strKeyTextField.Insert(n, "-")
End If
End If
End While
intlength = intlength - 5
End While
'' Define total variable with dashes
txtAntivirusCode.Text = strKeyTextField
'sets focus at the end of the string
txtAntivirusCode.Select(txtAntivirusCode.Text.Length, 0)
Output is : XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-
What I want : XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
You could just remove the last char in the string like that:
txtAntivirusCode.Text = strKeyTextField.Substring(0, strKeyTextField.Length - 1)
or
txtAntivirusCode.Text = strKeyTextField.Remove(strKeyTextField.Length - 1)
or
txtAntivirusCode.Text = strKeyTextField.Trim({" "c, "-"c})
or
txtAntivirusCode.Text = strKeyTextField.TrimEnd(CChar("-"))
If there is a possibility of a space at the end of the string use .Trim() before Substring and/or Remove
The other way from removing the last "-" is to not add the last "-", for example:
Dim s = "ABCDE-FGHIJKLMNOPQRSTUVWXYZ"
Dim batchSize = 5
Dim nBatches = 5
Dim nChars = nBatches * batchSize
' take out any dashes
s = s.Replace("-", "")
' make sure there are not too many characters
If s.Length > nChars Then
s = s.Substring(0, nChars)
End If
Dim sb As New Text.StringBuilder
For i = 1 To s.Length
sb.Append(s.Chars(i - 1))
If i Mod batchSize = 0 AndAlso i <> nChars Then
sb.Append("-")
End If
Next
Console.WriteLine(sb.ToString())
Console.ReadLine()
Outputs:
ABCDE-FGHIJ-KLMNO-PQRST-UVWXY

Blackjack: Won't add Dealer's Hand

I have a problem with my blackjack game in vb.net. This code I have will add the player's score perfectly, but when it comes to the dealer's score, it will not. It only takes the second card that the dealer has.
It is called with this:
addScore("p") 'add player's score
addScore("d") 'add dealer's score
And this is "addScore()":
Public Function card(player As String, index As Integer) As Label
Try
If player = "p" Then
Return GroupBox1.Controls.OfType(Of Label).Where(Function(l) l.Name = "YouCard" & index.ToString()).Single()
ElseIf player = "d" Then
Return GroupBox1.Controls.OfType(Of Label).Where(Function(l) l.Name = "DealerCard" & index.ToString()).Single()
End If
Catch
Return Nothing
End Try
End Function
Public Sub addScore(ByVal player As String)
Dim currScore As Integer
Dim result As Integer = 0
'Add Score
For value As Integer = 1 To 7
If card(player, value).Text = "A" AndAlso (currScore + 11) <= 21 Then
result = currScore + 11
ElseIf card(player, value).Text = "A" AndAlso (currScore + 1) <= 22 Then
result = currScore + 1
ElseIf IsNumeric(card(player, value).Text) Then
result = currScore + CInt(card(player, value).Text)
ElseIf card(player, value).Text = "" Then
result = result
Else
result = currScore + 10
End If
If player = "p" Then
YouScore.Text = result
Else
DealerScore.Text = result
End If
Next
End Sub
currScore shouldn't be there. Replace it with result
Public Sub addScore(ByVal player As String)
Dim result As Integer = 0
'Add Score
For value As Integer = 1 To 7
If card(player, value).Text = "A" AndAlso (result + 11) <= 21 Then
result = result + 11
ElseIf card(player, value).Text = "A" AndAlso (result + 1) <= 22 Then
result = result + 1
ElseIf IsNumeric(card(player, value).Text) Then
result = result + CInt(card(player, value).Text)
ElseIf card(player, value).Text = "" Then
result = result
Else
result = result + 10
End If
If player = "p" Then
YouScore.Text = result
Else
DealerScore.Text = result
End If
Next
End Sub

Algorithmn: Cut Company name into 3 Strings, did I miss a case?

Hello I wrote an algorithmn which should cut a companies name into 3 strings.
Input 1 String
Output 3 String.
Conditions:
String 1 2 and 3 shall not be longer then 35 signs.
If the Input string is longer then 105 it only shall be cut.
If you have fun and be interested in algorithmns it would be nice if you take a look at it.
I´m happy for every input
Cheers B101
Public Sub CompanyCut()
//3 output Strings
Dim var1 As String = ""
Dim var2 As String = ""
Dim var3 As String = ""
If Module1.insertdict("company").Length > 35 Then
Dim s1 As String = Module1.insertdict("company").ToString
If s1.Length > 105 Then
s1 = Microsoft.VisualBasic.Left(s1, 105)
End If
//Split String into array at every Whitespace
Dim pattern As String = "\s"
Dim sa() As String = Regex.Split(s1, pattern)
//Variables for loop
Dim i As Integer = 0
Dim varyn As Boolean = True
Dim varyn1 As Boolean = False
Dim varyn2 As Boolean = False
//loop which fills var1 var2 and var3 with arrayfields untill size 35
would be reached
For i = 0 To sa.Length - 1
If var1.Length < 35 AndAlso varyn = True Then
If var1.Length + 1 + sa(i).Length < 35 Then
var1 = var1 + " " + sa(i).ToString
Else
varyn = False
varyn1 = True
varyn2 = False
End If
End If
If var2.Length < 35 AndAlso varyn1 = True Then
If var2.Length + 1 + sa(i).Length < 35 Then
var2 = var2 + " " + sa(i).ToString
Else
varyn1 = False
varyn = False
varyn2 = True
End If
End If
If var3.Length < 35 AndAlso varyn2 = True Then
If var3.Length + 1 + sa(i).Length < 35 Then
var3 = var3 + " " + sa(i).ToString
Else
varyn2 = False
End If
End If
Next
//my idea was that if it has the same or bigger length all fields must
be in + the whitespaces
If var1.Length + var2.Length + var3.Length >= s1.Length Then
Module1.insertdict("Firma") = var1
Module1.insertdict("Name2") = var2
Module1.insertdict("Name3") = var3
Else
//this occurs when the string is smaller as 105 signs but not all
fields of the array could be placed in the variables.
Module1.insertdict("Failure") = "Company name need to split by user"
End If
Else
Module1.insertdict("Name2") = ""
Module1.insertdict("Name3") = ""
End If
End Sub

Calculate words value in vb.net

I have a textbox on a form where the user types some text. Each letter is assigned a different value like a = 1, b = 2, c = 3 and so forth. For example, if the user types "aa bb ccc" the output on a label should be like:
aa = 2
bb = 4
dd = 6
Total value is (12)
I was able to get the total value by looping through the textbox string, but how do I display the total for each word. This is what I have so far:
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter.ToUpper = "A" Then
letter_value = 1
End If
If letter.ToUpper = "B" Then
letter_value = 2
End If
If letter.ToUpper = "C" Then
letter_value = 3
End If
If letter.ToUpper = "D" Then
letter_value = 4
End If
If letter.ToUpper = "E" Then
letter_value = 5
End If
If letter.ToUpper = " " Then
letter_value = 0
End If
totalletter = totalletter + letter_value
Label1.Text = Label1.Text & letter_value & " "
txtBox2.Text = txtBox2.Text & letter_value & " "
Next letter_counter
This simple little routine should do the trick:
Private Sub CountLetters(Input As String)
Label1.Text = ""
Dim total As Integer = 0
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("a"c, 1)
dicLetters.Add("b"c, 5)
dicLetters.Add("c"c, 7)
For Each word As String In Input.Split
Dim wordtotal As Integer = 0
For Each c As Char In word
wordtotal += dicLetters(Char.ToLower(c))
Next
total += wordtotal
'Display word totals here
Label1.Text += word.PadRight(12) + "=" + wordtotal.ToString.PadLeft(5) + vbNewLine
Next
'Display total here
Label1.Text += "Total".PadRight(12) + "=" + total.ToString.PadLeft(5)
End Sub
This should give you an idea:
Dim listOfWordValues As New List(Of Integer)
For letter_counter = 1 To word_length
letter = Mid(txtBox1.Text, letter_counter, 1)
If letter = " " Then
totalletter= totalletter + letter_value
listOfWordValues.Add(letter_value)
letter_value = 0
Else
letter_value += Asc(letter.ToUpper) - 64
End If
Next letter_counter
totalletter = totalletter + letter_value
If Not txtBox1.Text.EndsWith(" ") Then listOfWordValues.Add(letter_value)
txtBox2.Text = txtBox2.Text & string.Join(", ", listOFWordValues);
You can try something like this. Assuming txtBox1 is the string the user enters and " " (space) is the word delimiter:
Dim words As String() = txtBox1.Text.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
Dim totalValue As Integer = 0
Dim wordValue As Integer = 0
For Each word As String In words
wordValue = 0
For letter_counter = 1 To word.Length
Dim letter As String = Mid(txtBox1.Text, letter_counter, 1)
Select letter.ToUpper()
Case "A":
wordValue = wordValue + 1
Case "B":
wordValue = wordValue + 2
' And so on
End Select
Next
totalValue = toalValue + wordValue
Next
The above code first takes the entered text from the user and splits it on " " (space).
Next it sets two variables - one for the total value and one for the individual word values, and initializes them to 0.
The outer loop goes through each word in the array from the Split performed on the user entered text. At the start of this loop, it resets the wordValue counter to 0.
The inner loop goes through the current word, and totals up the values of the letter via a Select statement.
Once the inner loop exits, the total value for that word is added to the running totalValue, and the next word is evaluated.
At the end of these two loops you will have calculated the values for each word as well as the total for all the worlds.
The only thing not included in my sample is updating your label(s).
Try this ..
Dim s As String = TextBox1.Text
Dim c As String = "ABCDE"
Dim s0 As String
Dim totalletter As Integer
For x As Integer = 0 To s.Length - 1
s0 = s.Substring(x, 1).ToUpper
If c.Contains(s0) Then
totalletter += c.IndexOf(s0) + 1
End If
Next
MsgBox(totalletter)
I would solve this problem using a dictionary that maps each letter to a number.
Private Shared ReadOnly LetterValues As Dictionary(Of Char, Integer) = GetValues()
Private Shared Function GetValues() As IEnumerable(Of KeyValuePair(Of Char, Integer))
Dim values As New Dictionary(Of Char, Integer)
Dim value As Integer = 0
For Each letter As Char In "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
value += 1
values.Add(letter, value)
Next
Return values
End Function
Public Function CalculateValue(input As String) As Integer
Dim sum As Integer = 0
For Each letter As Char In input.ToUpperInvariant()
If LetterValues.ContainsKey(letter) Then
sum += LetterValues.Item(letter)
End If
Next
Return sum
End Function
Usage example:
Dim sum As Integer = 0
For Each segment As String In "aa bb ccc".Split()
Dim value = CalculateValue(segment)
Console.WriteLine("{0} = {1}", segment, value)
sum += value
Next
Console.WriteLine("Total value is {0}", sum)
' Output
' aa = 2
' bb = 4
' ccc = 9
' Total value is 15