I am creating a program to generate numbers between a list of values.
Problem I am having is if the first number stats with a smaller value than the second value it will create an error, such as 1000 and 32 will say it doesnt work, or 532 and 64
I do not understand why or how to fix it
Private Sub Generate_Click(sender As System.Object,
e As System.EventArgs) Handles Generate.Click
'Displays to enter correct information if lower is <=
If Upper.Text <= Lower.Text Or Lower.Text >= Upper.Text Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
'If Upper range is higher than lower range then display numbers until total value is displayed
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= Upper.Text 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
End Sub
Basically you have to compare numeric value you are comparing string so it is happening.
And 'or' condition is not required in if statement so omit it.
please replace you code as follows.
if System.Convert.ToInt32(Upper.Text) <= System.Convert.ToInt32(Lower.Text) Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= System.Convert.ToInt32(Upper.Text) 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
With the If clause, you are doing a string comparison on numerical values. You need to cast them to integer values. And you are doing the same comparison twice which is unnecessary. Also there is a simpler way of generating random numbers between two integers.
I would encourage you to code with the "Option Strict On" declaration at the top of the page. The compiler will alert you when you attempt to make implicit conversions of which there are several in your code.
Dim iMinimum As Integer = Integer.Parse(Lower.Text)
Dim iMaximum As Integer = Integer.Parse(Upper.Text)
If iMaximum <= iMinimum Then
Number.Text = "Please enter correct info Upper # higher value than Lower #"
Else
Dim randomObject As Random = New Random
Number.Text = randomObject.Next(iMinimum, iMaximum).ToString
End If
Related
I am trying to create a simple counter that increases when the button is clicked.
What I would like is when the counter is clicked it displays "01", "02" etc.
I can create it already with "1", "2", but I would like to have a leading zero.
I have searched and found I can do this by converting the label to a string, but I cant seem to get the value to count?
If I change "count.text = counter" to "count.text = cot" it will display "01", but wont count. I'm guessing this is due to the fact its only displaying what is currently in the string but not increasing the value?
If I could get any guidance that would be great!
Many thanks!
Dim counter As Integer = 1
Dim cot As String = String.Format("{0:00}", counter)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter = cot + 1
count.Text = counter
End Sub
PadLeft is the key.
Dim number as Integer = 12
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 12
number = 2
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 02
The problem is, that you don't update your formatted number properly. It's only initialized a single time.
To increment the counter, use counter += 1 or counter = counter + 1 first. This will add 1 to the current value of the integer variable. Then modify the text of your Label by calling that formatting code again: count.Text = String.Format("{0:00}", counter).
This should get you started...
it converts the string into an integer. increments the number, converts it back into a string and then checks for a leading 0, if not found it adds it.
I will let you convert it into your button click for practise, as it should help you have a good understanding of the conversion between types :)
Sub string_counter()
Dim string_counter As String
string_counter = "00"
For x = 0 To 10
Debug.Print string_counter
string_counter = Int(string_counter) + 1
string_counter = Str(string_counter)
If Left(Trim(string_counter), 1) <> "0" Then
string_counter = "0" + Trim(string_counter)
End If
Next x
End Sub
I need to save Multiple(about 20-25) serial number of the specimen in my application. Sometimes serial number will be alphanumeric but will be sequential. I need a way out to increment alphanumeric serial numbers based on the first serial number entered.
My main problem is alphabet position and alphabet count keeps changing. Example : 10MG2015 20562MG0 MGX02526 etc etc
I tried but mine works when Alphabet are in starting position and when there are known number of alphabets. Here is my try
Dim intValue as integer
Dim serialno as string
Dim serialno1 as string
For i =0 to 20
Serialno1 = serialno.Substring(3)
Int32.TryParse(Serialno1, intValue)
intValue = intValue + 1
checkedox1.items.add(serialno.Substring(0,3) + intValue.ToString("D3"))
NEXT
Any help is highly appreciated. Thanks in advance
edit 1
Clarity : I want to increment alphanumeric string. Example : If first entered one is 10MG2015 then I should increment to 10MG2016, 10MG2017, 10MG2018, 10MG2019 and so on... For 20562MG0 it will be 20562MG1, 20562MG2 20562MG3 and so on...
Function FindSequenceNumber(SerialNumber As String) As Integer
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim result As Integer = -1
Dim m As Match = sequenceExpr.Match(SerialNumber)
If m.Success AndAlso Integer.TryParse(m.Groups(1).Value, result) Then
Return result
Else
'Throw exception, return -1, etc
End If
End Function
See it here:
https://dotnetfiddle.net/gO2nue
Note: the integer type doesn't preserve leading zeros. You may find it better to return a tuple with either the length of the original string, so you can pad zeros to the left if needed to match the original formatting.
Or maybe this:
Function IncrementSerial(SerialNumber As String) As String
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim m As Match = sequenceExpr.Match(SerialNumber)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Dim seq = (Integer.Parse(c.Value) + 1).ToString()
If seq.Length < c.Value.Length Then
seq = seq.PadLeft(c.Value.Length, "0"c)
End If
Dim result As String = ""
If c.Index > 0 Then result & = SerialNumber.Substring(0, c.Index)
result &= seq
If c.Index + seq.Length < SerialNumber.Length Then result &= SerialNumber.SubString(c.Index + seq.Length)
Return result
End Function
I am writing code for a form that is supposed to determine whether a value inputted by the user is valid as a check digit. They input a 13 digit number and it should determine whether or not the last value is valid as a check digit. I have written in the code for the check digit algorithm but I'm having trouble with comparing the value that the algorithm found with what the user input. I have tried using the substring method to compare the 13th number given by the user with the check digit that the algorithm determined but I am having issues with the syntax of everything.
This is the code I have been working on:
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim intDigit As Integer
Dim intTotalOdd As Integer
Dim intTotalEven As Integer
Dim intGrandTotal As Integer
Dim intRemainder As Integer
Dim intCheckDigit As Integer
If txtNumber.Text.Length = 13 Then
For intOdd As Integer = 1 To 11 Step 2
intTotalOdd += (intDigit * 3)
Next intOdd
For intEven As Integer = 0 To 10 Step 2
intTotalEven += intDigit
Next intEven
intGrandTotal = intTotalOdd + intTotalEven
intRemainder = intGrandTotal Mod 10
If intRemainder <> 0 Then
intCheckDigit = 10 - intRemainder
End If
If txtNumber.Text.Substring(12, 13) = intCheckDigit Then
lblStatus = "Valid"
Else
lblStatus = "Not Valid"
End If
End If
End Sub
I think the way I'm doing it should work but I don't have very much to reference on how I would go about making the syntax work. Will the way that I'm trying to do it work or do I need to go about it in a different way?
I am trying to create an application which will determine whether a string entered by user is a palindrome or not.
Is it possible to do without StrReverse, possibly with for next loop. That's what i have done so far.
Working one, with StrReverse:
Dim userInput As String = Me.txtbx1.Text.Trim.Replace(" ", "")
Dim toBeComparedWith As String = StrReverse(userInput)
Select Case String.Compare(userInput, toBeComparedWith, True)
Case 0
Me.lbl2.Text = "The following string is a palindrom"
Case Else
Me.lbl2.Text = "The following string is not a palindrom"
End Select
Not working one:
Dim input As String = TextBox1.Text.Trim.Replace(" ", "")
Dim pallindromeChecker As String = input
Dim output As String
For counter As Integer = input To pallindromeChecker Step -1
output = pallindromeChecker
Next counter
output = pallindromeChecker
If output = input Then
Me.Label1.Text = "output"
Else
Me.Label1.Text = "hi"
End If
While using string reversal works, it is suboptimal because you're iterating over the string at least 2 full times (as string reversal creates a copy of a string because strings are immutable in .NET) (plus extra iterations for your Trim and Replace calls).
However consider the essential properties of a palindrome: the first half of a string is equal to the second half of the string in reverse.
The optimal algorithm for checking a palindrome needs only iterate through half of the input string - by comparing value[n] with value[length-n] for n = 0 to length/2.
In VB.NET:
Public Shared Function IsPalindrome(value As String) As Boolean
' Input validation.
If value Is Nothing Then Throw New ArgumentNullException("value")
value = value.Replace(" ", "") // Note String.Replace(String,String) runs in O(n) time and if replacement is necessary then O(n) space.
' Shortcut case if the input string is empty.
If value.Length = 0 Then Return False ' or True, depends on your preference
' Only need to iterate until half of the string length.
' Note that integer division results in a truncated value, e.g. (5 / 2 = 2)...
'... so this ignores the middle character if the string is an odd-number of characters long.
Dim max As Integer = value.Length - 1
For i As Integer = 0 To value.Length / 2
If value(i) <> value(max-i) Then
' Shortcut: we can abort on the first mismatched character we encounter, no need to check further.
Return False
End If
Next i
' All "opposite" characters are equal, so return True.
Return True
End Function
"Write a program which reads in a start and an end value. The program then stores all the even numbers between these two values (inclusive) in an array. The user is then asked to select a number (n), the program should output the nth even number"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
number1 = InputBox("Enter first number")
number2 = InputBox("enter second number")
Any guidance on this would be much appreciated, I'm completely lost.
Ok, the edit is making more sense to me now. You were on the right track getting the first three inputs. Then we neeed to do 2 things to our inputs:
1) Get the even numbers within the range the user has given us
2) Return the nth term if it exists
I would approach the problem like this:
'Get our inputs
Dim number1 As Integer = CInt(InputBox("Enter first number"))
Dim number2 As Integer = CInt(InputBox("Enter second number"))
Dim nthTerm As Integer = CInt(InputBox("Enter Nth Term"))
Dim evenNumbers As New List(Of Integer)
'Now, we want to get a list of all the even numbers within n1 to n2 range
For i As Integer = number1 To number2
'if the number divided by 2 has a remainder of 0, then it's an even number
If i Mod 2 = 0 Then evenNumbers.Add(i)
Next
'Now that we have all the even #s, try to return the nth one as long as it exists
Try
'We substract 1 from the nthTerm entered by used to account for list's 0-based index
MsgBox(evenNumbers(nthTerm - 1).ToString)
Catch ex As Exception
MsgBox("Nth Term out of bounds")
End Try