Converting Check Amount To Words Using Case/Methods - vb.net

I am working on a project for my Visual Basic class, which is to create a digital check. The assignment requires us to input a check amount, which translates into words. In example, $1,200.00 needs to output "One thousand two hundred dollars"
For the most part, my code works. I'm using a switch statement. The original assignment was to have our check go up to a 9,999 value, but as we continue to build, we need to be able to convert up to 99,999.
As I said, I've been using a series of case statements, but realize that this is a very "hard code" way of doing this and would like create a method that can check these type of things for me, however I'm still new to Visual Basic and don't really have a good idea where to start or what is applicable in this scenario (we don't really have an example to go by.)
Here is my WriteCheck method that does the assigning/converting for the most part.
'Convert check value from a text field to a double'
Try
checkValue = checkInput.Text
Catch ex As InvalidCastException
MessageBox.Show("You must enter a numbers to write a check.")
End Try
'Operation to convert number to String'
thousands = checkValue \ 1000
hundreds = checkValue Mod 1000
hundreds = hundreds \ 100
tens = checkValue Mod 100
tens = tens \ 10
ones = checkValue Mod 10
ones = ones \ 1
'Case for thousands'
Select Case thousands & hundreds & tens
Case 1
tempStringT = "One"
Case 2
tempStringT = "Two"
Case 3
tempStringT = "Three"
Case 4
tempStringT = "Four"
Case 5
tempStringT = "Five"
Case 6
tempStringT = "Six"
Case 7
tempStringT = "Seven"
Case 8
tempStringT = "Eight"
Case 9
tempStringT = "Nine"
End Select
'Case for hundreds'
Select Case hundreds
Case 1
tempStringH = "one"
Case 2
tempStringH = "two"
Case 3
tempStringH = "three"
Case 4
tempStringH = "four"
Case 5
tempStringH = "five"
Case 6
tempStringH = "six"
Case 7
tempStringH = "seven"
Case 8
tempStringH = "eight"
Case 9
tempStringH = "nine"
End Select
'Case for tens'
Select Case tens Or ones
Case 1
tempStringTens = "one"
Case 2
tempStringTens = "twenty"
Case 3
tempStringTens = "thirty"
Case 4
tempStringTens = "fourty"
Case 5
tempStringTens = "fifty"
Case 6
tempStringTens = "sixty"
Case 7
tempStringTens = "seventy"
Case 8
tempStringTens = "eighty"
Case 9
tempStringTens = "ninety"
End Select
If tempStringTens <> "one" Then
'Case for ones'
Select Case ones
Case 1
tempStringO = "one"
Case 2
tempStringO = "two"
Case 3
tempStringO = "three"
Case 4
tempStringO = "four"
Case 5
tempStringO = "five"
Case 6
tempStringO = "six"
Case 7
tempStringO = "seven"
Case 8
tempStringO = "eight"
Case 9
tempStringO = "nine"
End Select
lblConverted.Text = tempStringT & " thousand " & tempStringH & " hundred " & tempStringTens & " " & tempStringO & " dollars " & change & "/100"
End If
If tempStringTens = "one" Then
Select Case ones
Case 1
tempStringO = "eleven"
Case 2
tempStringO = "twelve"
Case 3
tempStringO = "thirteen"
Case 4
tempStringO = "fourteen"
Case 5
tempStringO = "fifteen"
Case 6
tempStringO = "sixteen"
Case 7
tempStringO = "seventeen"
Case 8
tempStringO = "eighteen"
Case 9
tempStringO = "nineteen"
End Select
lblConverted.Text = tempStringT & " thousand " & tempStringH & " hundred " & tempStringO & " dollars"
End If
End Sub

This is my approach to the problem. The solution can be easily scaled up or down by adding or removing items in BigNumbers and upping the scope of num beyond Long if necessary. (As written, it will work for numbers up to 999,999,999,999,999.)
Public Function NumberToText(ByVal num As Long) As String
Dim BigNumbers() As String = {"", " Thousand", " Million", " Billion", " Trillion"}
Dim TextParts() As String = {}
If num < 0 Then
Return "Checks cannot be written for negative amounts."
ElseIf num >= 10 ^ ((BigNumbers.Length) * 3) Then
Return "This number exceeds the current maximum value of " & NumberToText(10 ^ ((BigNumbers.Length) * 3) - 1) & "."
End If
Dim LoopCount As Integer = 0
While num >= 1000
ReDim Preserve TextParts(TextParts.Length)
If num Mod 1000 > 0 Then
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num Mod 1000) & BigNumbers(LoopCount)
End If
num = num \ 1000
LoopCount += 1
End While
ReDim Preserve TextParts(TextParts.Length)
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num) & BigNumbers(LoopCount)
If Array.IndexOf(TextParts, "Error") > -1 Then
Return "An unknown error occurred while converting this number to text."
Else
Array.Reverse(TextParts)
Return Join(TextParts)
End If
End Function
Private Function ThreeDigitText(ByVal num As Integer) As String
If num > 999 Or num < 0 Then
Return "Error"
Else
Dim h As Integer = num \ 100 'Hundreds place
Dim tempText As String = ""
If h > 0 Then
tempText = OneDigitText(h) & " Hundred"
End If
num -= h * 100
If num > 0 And Not tempText = "" Then
tempText &= " "
End If
If num > 9 And num < 20 Then
Dim DoubleDigits() As String = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
Return tempText & DoubleDigits(num - 10)
Else
Dim TensPlace() As String = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
Dim t As Integer = num \ 10 'Tens place
num -= t * 10
If t > 1 Then
tempText &= TensPlace(t - 2)
If num > 0 Then
tempText &= " "
End If
End If
If num > 0 Then
tempText &= OneDigitText(num)
End If
Return tempText
End If
End If
End Function
Private Function OneDigitText(ByVal num As Integer) As String
If num > 9 Or Num < 0 Then
Return "Error"
Else
Dim SingleDigits() As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Return SingleDigits(num)
End If
End Function
Since this is for school, you will probably want to adapt parts of my code to your own rather than copy the whole thing. (Teachers can usually tell when you get code off the internet, especially if you can't explain every line.) If you have any questions about it, send them to the email listed in my profile.

Related

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

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)

how to convert combobox item into value and calculate it

I want to convert selected item in combobox into a number and calculate it.
I got message like this when i try to start my vb.net program.
Conversion from string "< 20 " to type 'Integer' is not valid
Any help is greatly appreciated.
this is my code:
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim LHR As Integer
Dim TipeRetak As Integer
Dim LbRetak As Integer
Dim LuKer As Integer
Dim Alur As Integer
Dim Tambal As Integer
Dim Kasar As Integer
Dim amblas As Integer
Select Case ComboLHR.SelectedIndex
Case "< 20 "
LHR = 0
Case "20 - 50"
LHR = 1
Case "50 - 200"
LHR = 2
Case "200 - 500"
LHR = 3
Case "500 - 2000"
LHR = 4
Case "2000 - 5000"
LHR = 5
Case "5000 - 20000"
LHR = 6
Case "20000 - 50000"
LHR = 7
Case "> 50000"
LHR = 8
End Select
Select Case ComboTipeRetak.SelectedIndex
Case "Buaya"
TipeRetak = 5
Case "Acak"
TipeRetak = 4
Case "Melintang"
TipeRetak = 3
Case "Memanjang"
TipeRetak = 1
Case "Tidak Ada"
TipeRetak = 1
End Select
Select Case ComboLebarRetak.SelectedIndex
Case "> 2 mm"
LbRetak = 3
Case "1 - 2 mm"
LbRetak = 2
Case "< 1 mm"
LbRetak = 1
Case "Tidak Ada"
LbRetak = 0
End Select
Select Case ComboLuasKerusakan.SelectedIndex
Case "> 30%"
LuKer = 3
Case "10 - 30%"
LuKer = 2
Case "< 10%"
LuKer = 1
Case "0"
LuKer = 0
End Select
Select Case ComboKedalamanAlur.SelectedIndex
Case "> 20 mm"
Alur = 7
Case "11 - 20 mm"
Alur = 5
Case "6 - 10 mm"
Alur = 3
Case "0 - 5 mm"
Alur = 1
Case "Tidak Ada"
Alur = 0
End Select
Select Case ComboTambal.SelectedIndex
Case ">30 %"
Tambal = 3
Case "20 - 30 %"
Tambal = 2
Case "10 - 20%"
Tambal = 1
Case "< 10%"
Tambal = 0
End Select
Select Case ComboKekasaran.SelectedIndex
Case "Desintegration"
Kasar = 4
Case "Pelepasan Butir"
Kasar = 3
Case "Rough(Hungry)"
Kasar = 2
Case "Fatty"
Kasar = 1
Case "Close Texture"
Kasar = 0
End Select
Select Case ComboAmblas.SelectedIndex
Case "> 5/100 m"
amblas = 4
Case "2 - 5/100 m"
amblas = 2
Case "0 - 2/100 m"
amblas = 1
Case "Tidak Ada"
amblas = 0
End Select
Dim comand As New MySqlCommand("INSERT INTO `tb_bnkt`(`nomor`, `Nama`, `kondisi prioritas`) VALUES (#nomor,#NamaRuas,#kondisi)", Connector)
comand.Parameters.Add("#nomor", MySqlDbType.VarChar).Value = TextNomor.Text
comand.Parameters.Add("#NamaRuas", MySqlDbType.VarChar).Value = ComboNamaRuas.Text
comand.Parameters.Add("#kondisi", MySqlDbType.VarChar).Value = 17 - (Val(LHR + TipeRetak + LbRetak + LuKer + Alur + Tambal + Kasar + amblas))
If comand.ExecuteNonQuery() = 1 Then
MessageBox.Show("Data disimpan")
Loading()
TextNomor.Clear()
ComboNamaRuas.Text = String.Empty
ComboLHR.Text = String.Empty
ComboTipeRetak.Text = String.Empty
ComboLebarRetak.Text = String.Empty
ComboLuasKerusakan.Text = String.Empty
ComboKedalamanAlur.Text = String.Empty
ComboTambal.Text = String.Empty
ComboKekasaran.Text = String.Empty
ComboAmblas.Text = String.Empty
Else
MessageBox.Show("Error")
End If
End Sub
With simple class and data-binding you can simplify your code a little bid and get rid of current problem as well.
Public Class MyItem
Public ReadOnly Name As String
Public ReadOnly Value As Integer
Public Sub New(name As String, value As Integer)
Me.Name = name
Me.Value = value
End Sub
End Class
' Then in constructor create collection of values and bind it ot the combobox
Dim LHRValues As New List(Of MyItem) From
{
New MyItem("< 20 ", 0),
New MyItem("20 - 50", 1),
New MyItem("50 - 200", 2),
New MyItem("200 - 500", 3),
New MyItem("500 - 2000", 4),
New MyItem("2000 - 5000", 5),
New MyItem("5000 - 20000", 6),
New MyItem("20000 - 50000", 7),
New MyItem("> 50000", 8)
}
ComboLHR.DisplayMember = "Name" ' Property Name will be used as a text
ComboLHR.ValueMember = "Value" ' Property Value will be used as a value
ComboLHR.DataSource = LHRValues
' Then in the code where you need selected value
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim selectedLHR As Integer = DirectCast(ComboLHR.SelectedValue, Integer)
' Other selected values
End Sub
You only need to cast ComboLHR.SelectedValue to the type you expect (Integer), because SelectedValue is of type object. I hope you have Option Strict set On.

SpellNum_Dollar module converting only one part, second part

I wanted a visual basic in excel code to convert numbers into text. The code is already available on Microsoft site, but I wanted more specific one. So someone helped me and edited the Microsoft's code. It worked fine, but one critical problem occurred. I asked him for help but he is not responding anymore.
The problem is that if there is two parts, only the first part is written.
For example: 284,323.00 is written as "Two hundred eighty-four thousand dollars only"
877,666.00 is written as "Eight hundred seventy-seven thousand dollars only"
I want the full number to be converted into text like this : "877,666.00 > Eight hundred seventy-seven thousand six hundred sixty-six dollars only"
Can you help me correct the code?
This is the code:
Option Explicit
'Main Function
Function SpellNum_Dollar(ByVal MyNumber As Variant) As String
Dim Dollars, Cents, Temp, D
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert Cents and set MyNumber to dollars amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & D
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop
Select Case Dollars
Case ""
Dollars = "No Dollars"
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars & " Dollars"
End Select
Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and One Cent"
Case Else
Cents = " and " & Cents & " Cents"
End Select
SpellNum_Dollar = LowerCaseWords(Dollars & Cents)
End Function
' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function
' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten"
Case 11: Result = "Eleven"
Case 12: Result = "Twelve"
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen"
Case 15: Result = "Fifteen"
Case 16: Result = "Sixteen"
Case 17: Result = "Seventeen"
Case 18: Result = "Eighteen"
Case 19: Result = "Nineteen"
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty-"
Case 3: Result = "Thirty-"
Case 4: Result = "Forty-"
Case 5: Result = "Fifty-"
Case 6: Result = "Sixty-"
Case 7: Result = "Seventy-"
Case 8: Result = "Eighty-"
Case 9: Result = "Ninety-"
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
If Right(Result, 1) = "-" Then
Result = Left(Result, Len(Result) - 1)
End If
GetTens = Result
End Function
' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One"
Case 2: GetDigit = "Two"
Case 3: GetDigit = "Three"
Case 4: GetDigit = "Four"
Case 5: GetDigit = "Five"
Case 6: GetDigit = "Six"
Case 7: GetDigit = "Seven"
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine"
Case Else: GetDigit = ""
End Select
End Function
Function LowerCaseWords(MyNumber As String) As String
'Splits the number into an array and then loops through the array, starting at the second word, and lower cases all of them
'Just need to check if the first word has a dash, if so, the first letter after the dash will be lower cased
Const ArrayLoopStart As Long = 1
Dim WordArray As Variant
Dim WordCounter As Long
Dim FindDash As Long
WordArray = Split(MyNumber, " ")
FindDash = InStr(1, WordArray(0), "-")
If FindDash > 0 Then
WordArray(0) = Left(WordArray(0), FindDash) & LCase(Mid(WordArray(0), FindDash + 1, 1)) & Right(WordArray(0), Len(WordArray(0)) - 1 - FindDash)
End If
For WordCounter = ArrayLoopStart To UBound(WordArray)
WordArray(WordCounter) = LCase(WordArray(WordCounter))
Next WordCounter
LowerCaseWords = Join(WordArray, " ")
End Function

How to make a "key generator" knowing the formula

I have the formula to check 9 integers,
First digit(d1) must be: 1, 2, 5, 6, 8 or 9
Last digit(d9) must be: 0 or 9
9xd1+8xd2+7xd3+6xd4+5xd5+4xd6+3xd7+2xd8+d9 mod 11 = 0
I can "validate" the key, but how can I generate more of this, knowing the conditions for it to be right?
How can I generate 9 different integers from 0 to 9 and check them under this formula?
Thanks for helping!
Generate the first 7 digits randomly, calculating the formula for those digits.
Set the 9th digit's value to 9, and add it to the formula.
Calculate a value for the 8th digit based on the mod of the result of the formula that causes the result of the formula to be mod 11 = 0.
For the exception case where attempting to do this causes mod 11 = 9, set the 9th digit to 0.
Implementation:
Private randGen As New Random()
Function GenNum() As Integer
Dim digits(0 To 8) As Integer
GenNum = 0
Dim checkSum As Integer
digits(0) = randGen.Next(6) + 1
If digits(0) >= 3 Then digits(0) += 2
If digits(0) >= 7 Then digits(0) += 1
checkSum += digits(0) * 9
For d As Integer = 1 To 6
digits(d) = randGen.Next(10)
checkSum += digits(d) * (9 - d)
Next
digits(8) = 9
checkSum += digits(8)
If (checkSum Mod 11) Mod 2 = 1 Then
digits(7) = (11 - (checkSum Mod 11)) \ 2
Else
digits(7) = ((12 - (checkSum Mod 11)) \ 2 + 4) Mod 10
End If
checkSum += digits(7) * 2
If checkSum Mod 11 = 9 Then digits(8) = 0
Dim pow10 As Integer = 1
For d As Integer = 8 To 0 Step -1
GenNum += pow10 * digits(d)
pow10 *= 10
Next
End Function
I can help you to generate integers from 0 to 9.
here is how your form should look like:
and here is the code:
Public Class Form1
Dim NumRandom As Random = New Random
Dim X, Y, Z As Integer
Private Sub GenerateBUT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBUT.Click
Dim a(9), i, j, RN As Integer
Dim flag As Boolean
flag = False
i = 1
a(j) = 1
Do While i <= 9
Randomize()
RN = CInt(Int(9 * Rnd()) + 1)
For j = 1 To i
If (a(j)) = RN Then
flag = True
Exit For
End If
Next
If flag = True Then
flag = False
Else
a(i) = RN
i = i + 1S
End If
Loop
Label1.Text = a(1)
Label2.Text = a(2)
Label3.Text = a(3)
Label4.Text = a(4)
Label5.Text = a(5)
Label6.Text = a(6)
Label7.Text = a(7)
Label8.Text = a(8)
Label9.Text = a(9)
Z = Label4.Text
Y = Label5.Text
X = Z + Y
X = X - Label3.Text
If X > 1 And X < 10 Then
X = NumRandom.Next(1, 7)
If X = 1 Then
Label1.Text = "0"
ElseIf X = 2 Then
Label2.Text = "0"
ElseIf X = 3 Then
Label3.Text = "0"
ElseIf X = 4 Then
Label4.Text = "0"
ElseIf X = 5 Then
Label5.Text = "0"
ElseIf X = 6 Then
Label6.Text = "0"
ElseIf X = 7 Then
Label7.Text = "0"
End If
End If
End Sub
End Class

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