Confused? How to find even numbers between two numbers? VB.NET - vb.net

How do I find the even numbers from 6 through 16.
The thing is I'm working with events. How should I do this? I did a lot of research and found some code that might work but I'm not sure how it works. (I'm by no means advanced with vb.net - I'm just trying to finish this course.)
What I did find was that I have to use MOD? I'm not even really sure how to use that with an event? Any code would be awesome to getting me on the road to finish this assignment.
I took this code out of a program that had to find even numbers and it works great but the only downfall is that it starts from 1 and then whatever number you want it to stop at. I only need 6 through 16 ..
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Diagnostics
Module Module1
Private Delegate Sub numManip()
Sub Main()
Dim evennumber As numManip
Dim allNumbers As [Delegate]
evennumber = New numManip(AddressOf Even)
allNumbers = [Delegate].Combine(evennumber)
allNumbers.DynamicInvoke()
End Sub
Sub Even()
Console.Clear()
Dim counter As Integer = 2
Console.WriteLine("Even Numbers")
Console.WriteLine("Please Enter the Number you Wish to End at: ")
Dim number As Integer = Console.ReadLine()
Console.Clear()
Console.WriteLine("All Even Numbers From 6 to " & number)
Do Until counter > number
Console.WriteLine(counter)
counter += 2
Loop
Console.WriteLine("Press Enter to Continue...")
Console.ReadLine()
End Sub
Public Enum Numbers
Unset
Prime
Composite
End Enum
End Module

This code would work great for you.. You just need to change the logic a little. This code start at 2, since counter is 2. You can of course change that number to start at whatever you want using the same logic as you enter the last number (if you can enter the last, you can of course enter the first ;) ).
The other thing you have to change, is to use the mod operator to get the remainder of the division, since when you start at an add number, you will have problem is you always assume that your first number is even...
anyway.. if you want to start at 6, just change this line
Dim counter As Integer = 2
to
Dim counter As Integer = 6
and if you always want to finish at 16 just change this
Console.WriteLine("Even Numbers")
Console.WriteLine("Please Enter the Number you Wish to End at: ")
Dim number As Integer = Console.ReadLine()
Console.Clear()
to this:
Dim number As Integer = 16

Why do you say you are using events? First of all, none of the code you showed uses events, but even if your code to calculate the numbers was in an event handler, it wouldn't change anything. If however, your code needs to raise events each time it finds an even number, or raises an event when it's done, that changes things a little.
Everything you are doing in the Main method is pointless. All it accomplishes is to call the Even method, which you could do very simply like this:
Sub Main()
Even()
End Sub
Even if you needed to use a delegate for some reason, which there doesn't appear to be any reason why you do, all you would have to do is something like this:
Sub Main()
Dim evenDelegate As numManip = New numManip(AddressOf Even)
evenDelegate.Invoke()
End Sub
In your Even method, I would use a For loop, not a Do Loop. If you find the first even number, you could step by 2, such as
For i As Integer = evenStartingNumber To endingNumber Step 2
Next
Otherwise, you need to loop through every number (stepping by 1), and then test each number to see if it's even or odd. Such as:
For i As Integer = startingNumber To endingNumber
If IsEven(i) Then
End If
Next
To determine if a number is even or odd, that's where the Mod operator comes in. Mod returns the remainder from a division operation (the left over fraction). So for instance, 10 divided by 4 is 2 with a remainder of 2. When you divide any even number by 2, the remainder is always zero, so if x Mod 2 = 0, then x is an even number.

Without diving in to the other parts of the assignment, you check for even numbers using 'Mod 2'
If (myNum Mod 2) = 0 Then
'It's even!
Else
'It's not!
End If
For the Events part of it: I don't want to give you code to cut and paste, but consider this idea: your main sub iterates through the number 6..16. On each number, you raise a custom event. Inside the event you output to the console if its even.
Class NumEventArgs
Inherits EventArgs
Public Property Num() As String
Public Sub New(num As Integer)
Me.Num = num
End Sub
End Class
Public Event NumCheckEvent(sender As Object, e As NumEventArgs)
Sub Main()
AddHandler NumCheckEvent, AddressOf NumCheckEventHandler
For i = 6 To 16 Step 2
RaiseEvent NumCheckEvent(Nothing, New NumEventArgs(i))
Next
End Sub
Sub NumCheckEventHandler(sender As Object, e As NumEventArgs)
If e.Num Mod 2 = 0 Then
Console.WriteLine("Even!")
End If
End Sub

Related

VB.net - 5 threads reading/writing to the same variable

I have an app that uses 5 concurrent threads to perform tasks. The threads will need to read from a list of items and pick the next available one. As soon as they've done so, they need to add one to the counter so that the next thread is able to pick the next one. I understand i will need to use something like BlockingCollection to do this so that 2 threads dont end up picking the same number and then both incrementing by one.
I'm a little stuck as to how this will work. I have declared by new BlockingCollection object but not sure where to proceed from here? Any help is much appreciated. Thanks.
It sounds to me that you should be using a ConcurrentQueue(Of T). The whole point of a queue is that you can pick the next item off the front so if you use a queue data structure then there's no incrementing of any counter required. On top of that functionality provided by the Queue(Of T) class, the ConcurrentQueue(Of T) class is also thread-safe. Sounds rather like exactly what you need. Just call TryDequeue each time you want an item and it will return False when there are no more.
Try the following in a new Console Application project to see the principle in action:
Imports System.Collections.Concurrent
Imports System.Threading
Module Module1
'A thread-safe queue containing numbers from 1 to 100.
Private numbers As New ConcurrentQueue(Of Integer)(Enumerable.Range(1, 100))
'Random number generator.
Private rng As New Random
Sub Main()
'Read the queued numbers using five threads.
For i = 1 To 5
Call New Thread(AddressOf DisplayNumbers).Start()
Next
Console.ReadLine()
End Sub
Private Sub DisplayNumbers()
Dim number As Integer
'Try to get the next number until there are no more.
Do While numbers.TryDequeue(number)
'Display the number and the thread that read it.
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}; Number: {number}")
'Wait a random time period.
Thread.Sleep(rng.Next(500, 1000))
Loop
End Sub
End Module

Using loops to allow me to enter several numbers into a console application program, and then do calculations

This is basically the details of my assignment
Using loops, write a visual basic console application will allow you to enter an arbitrary amount of numbers. The application should then calculate the average of all the numbers entered by the user. Input should be validated using loops to ensure the data entered is a valid number. If an entered value is not valid, the user should be prompted until they enter a valid number.
Output the following to the Console
Sum of the Numbers Entered:
Total Number of Numbers Entered:
Average of Numbers Entered:
The way I am thinking about doing it is:
Have the user prompt for a number
check to see if it's numeric or not
if its not numeric it prompts again
if it is numeric, it prompts for more numbers
have an option where a user can type a key or keyword, and the program stops collecting numbers, and does the calculations, outputting the following three things that were required.
My issue is that I can't really visualize on how to do it, or really how to write it in such a way. My initial issue with learning so far is not being able to see how it works, or an example of the code, but when I do - I can understand it and use it efficiently. I just have trouble visualizing how to do/write it.
Dim str_num As String
Dim int_num As Integer
Dim int_counter As Integer
Sub Main()
Console.BackgroundColor = ConsoleColor.DarkBlue
Console.ForegroundColor = ConsoleColor.White
Console.Clear()
Do
Console.WriteLine("enter a number") 'prompts user to enter a number, followed by it storing in a variable.
str_num = Console.ReadLine
If Not IsNumeric(str_num) Then
int_num = str_num
Console.ReadKey()
End If
Loop
End Sub
Comments and explanations in-line.
Sub Main()
Dim num As Integer
'With a list, unlike an array, we don't have to know beforehand how many items we are going to add.
Dim lst As New List(Of Integer)
Do
Console.WriteLine("Enter a whole number.")
'A nested Do will test for a proper number
Do
'Integer.TryParse will return true if a valid number was entered and fill in the
'num variable with that number
If Integer.TryParse(Console.ReadLine, num) Then
'Since we have a valid number we add it to the lst
lst.Add(num)
'and exit the inner Do
Exit Do
Else
'If it isn't valid, we ask again for an input, the inner loop continues until we get a valid input
Console.WriteLine("Sorry, not a valid number. Please try again")
End If
Loop
Console.WriteLine("Is that enough numbers? Yes, No")
'Call .ToUpper on the input so we don't have to depend on what case the user typed in
If Console.ReadLine.ToUpper = "YES" Then
Exit Do
End If
Loop
'We can use the .Sum method and .Average method of the list to do the calculaion
Dim sumNum = lst.Sum()
'I have used Interpolated strings indicated by the $. These allow you to insert a variable
'surrounded by braces {} directly into a string.
'In Visual Studio prior to version 2015
'use Console.WriteLine(String.Format("The sum of the numbers you entered is {0}", sumNum))
Console.WriteLine($"The sum of the numbers you entered is {sumNum}")
Dim avgNum = lst.Average()
Console.WriteLine($"The average of the numbers your entered is {avgNum}")
Console.ReadLine()
End Sub
You look like you want to code it yourself, but miss a couple resources. I'll give you resources. You'll implement the logic. Deal?
Here's a way to get an input from the user and verify if it's really a number:
Dim userInput As String
Console.WriteLine("Enter a number:")
userInput = Console.ReadLine()
Dim inputAsInteger As Integer = 0
If Not Int32.TryParse(userInput, inputAsInteger) Then 'TryParse returns a Boolean which reads True if it worked
Console.WriteLine("Hey, that wasn't a number!")
End If
Here's a loop logic which you can use to gather your inputs:
Dim stopLooping As Boolean = False
Dim i As Integer = 0 'I'll count the loops with this integer, but the exit condition can be anything
Do
'Some code which do your stuff
'At some point, a condifion can flip stopLooping to True when you want the loop to stop
Console.WriteLine("Loop number " & i.ToString)
If i > 10 Then
stopLooping = True
End If
Loop Until stopLooping
Now you should be able to figure out something out of these tools, right? I'm sure you will. Have fun!

How to loop a sub w/ a variable value?

I'm creating a program that outputs a randomly generated password in which the user has jurasdiction over how many characters they want their password to be. How would i go about taking the input from the user and then looping the subroutine (which generates a single random character)? Any help would be much appreciated, thank you!
' this is the code for my input where n = the no. of characters the user wants in their pasword
Public Sub inp()
Console.WriteLine("How many characters do you want in your password?
(up to 20 allowed)")
n = Console.ReadLine()
End Sub
'this is the simple sub that generates a random number from which a character from my database is chosen
Public Sub randi()
Randomize()
i = Rnd() * 92
End Sub
Let us think about the steps envolved.
Ask user for a number
Place the response in a variable.
Create a random string with n characters
I looks like you have taken care of 1 and 2.
Now let's break down number 3 into tasks.
What characters do you want to include.
Uppercase letters? Lowercase letters? Numbers? Punctuation?
An ASCII table will tell you that there are readable characters from ASCII 33 to 126.
If you were to ask for a random number in the range 33 to 126 then change it to the character it represnts, it would be a start.
Luckily .net provides a Random class.
First we will need to get an instance of that class to use its methods.
Private rnd As New Random
Now we have a variable holding an instance of the random class so we can use any of the classed properties and methods.
There is a method, .Next(Int32, Int32), that will produce a random number in a range.
The first parameter is the bottom number in the range and the second is one more than the top number.
Going back to ASCII table we need a random number like this
rnd.Next(33, 125)
Next we need to change the result to a character.
Convert.ToChar(Ascii number)
The next problem is to get the number of characters the user asked for. Remember n.
We can do this is a For...Next loop.
Inside the loop we want to build a string with these random characters. This could be done with an ampersand equals but every time you changes a string the compiler has to throw away the old string and create an entirely new one because strings are immutable. To solve this .net has provided a StringBuilder class. We create an instance of this class and then use the .Append method to add the characters to the sb.
After the loop we change the StringBuilder to a regular string and return it to the calling code.
Public Sub Main()
Console.WriteLine("How many characters do you want in your password?
(up to 20 allowed)")
Dim n As Integer = CInt(Console.ReadLine())
Dim Pword As String = GetRandomString(n)
Console.WriteLine(Pword)
End Sub
Private rnd As New Random
Private Function GetRandomString(stringLength As Integer) As String
Dim sb As New StringBuilder
For c = 1 To stringLength
Dim newAscii = rnd.Next(33, 127)
Dim newChr = Convert.ToChar(newAscii)
sb.Append(newChr)
Next
Return sb.ToString
End Function
In a real application you would have to check if the user entered a valid number. An Integer.TryParse and a check for 0 would probably do it.

Vb Guessing Game Random generator broken

In my code,I have now realised I have to use the New Random function, my code was working before with the Randomize and then the numbers but now it comes up with loads of errors and wont even let me run the program. I think it is only a small error but I just need some help to get the final bit going
Heres the code and thanks for any help :)
I cannot get the code to work with the randomly generated number and I have to use the New Random function I cannot use randomize() Does anybody know how to help here is the code.
Dim timestook As Int32 = 1
Dim usersguess As Integer
Dim value = New Random(0 - 19)
Console.WriteLine("You have to guess this number. It is between 1 and 20. Good Luck !")
usersguess = Console.ReadLine()
'keep looping until they get the right value
While usersguess <> value
'now check how it compares to the random value
If usersguess < value Then
timestook = timestook + 1
Console.WriteLine("You're too low. Go higher ")
ElseIf usersguess > value Then
Console.WriteLine("You're too high. Go Lower.")
timestook = timestook + 1
End If
'If they are wrong the code will run again,after telling the user if they are too high or too low.
usersguess = Console.ReadLine()
End While
' Console.WriteLine("You're correct. Well Done")
If usersguess = value Then
Console.WriteLine("You took,{0}", timestook)
End If
Console.ReadLine()
End Sub
You'll want to do some googling on how to use random numbers. Your problem is that you aren't creating a Random object to handle the random number generation.
Here's how you can fix your code:
Dim randNumGen As New Random() 'Create Random object
Dim value As Integer = randNumGen.Next(0, 20) 'set value equal to a new random number between 0-19
Please note that this code could be further refactored for readability and simplicity (like changing timestook = timestook + 1 to timestook += 1 and selecting better variable names like numberOfGuesses as opposed to timestook, etc.
The expression New Random(0-19) does not do at all what you think it does, name it does NOT return an integer. Instead, it creates an instance of a Random object, which is a type that knows how to create new random values. The 0-19 part of the expression is the seed for the Random object's constructor, and is the same as just passing the value -19.
This looks like it's either homework or personal practice, so I feel like you will be better served in this case with a separate example using the Random type for reference than you would if I fixed the code sample in the question for you:
Dim rnd As New Random()
For i As Integer = 0 To 10
Console.WriteLine(rnd.Next(0, 20))
Next i
It's also worth mentioning here that you typically only want one Random object for your entire program, or at least only one Random object for each logical part of your program. Creating new Random objects resets the seeds, and for best results you want to follow the same seed on subsequent calls to the same instance for a while.

VB.net Console - Displaying a random number that was generated

I'm making a simple text based adventure in VB.net console that includes combat. In the fight scenes I want the game to generate a random number that determines how much damage you.
This is my current code:
Module Module1
Dim rng As New Random
Dim strmod As Integer = 1
Dim yourhit As Integer
Sub Main()
Console.WriteLine("Welocome to the training grounds!")
yourhit = (rng.Next(1, 4) + strmod)
Console.WriteLine("You hit the dummy and deal {0} damage to it!",
yourhit)
End Sub
End Module
Now i'm wondering if its possible for my randomly generated number to be displayed without it being entered into another variable (in this case the yourhit variable). I've tried simply by having rng instead of yourhit but that a message saying You hit the dummy and deal System.Random damage to it!
I'm new to visual basic so any help would be appreciated!
You should just be able to do:
Console.WriteLine("You hit the dummy and deal {0} damage to it!",
(rng.Next(1, 4) + strmod))