Visual Basic - function to check if number is binary or not - vb.net

Im code newbie and im stuck with this code. It appears that i always get True as response from this function. What am i doing wrong ?
Private Function binary() As Boolean
Dim number, temp As Integer
Dim status As Boolean
TextBox1.Text = number
status = True
While (True)
If (number = 0) Then
Exit While
Else
temp = number Mod 10
If (temp > 1) Then
status = False
Exit While
End If
number = number / 10
End If
End While
Return status
End Function

You have your assignment the wrong way around:
TextBox1.Text = number
With this, number will always be 0, its initial value, so your While loop exits immediately, every time. It should be:
number = Convert.ToInt32(TextBox1.Text)
Or better yet, pass it in as a parameter to the function:
Private Function binary(number as Integer) As Boolean
Dim temp As Integer
Dim status As Boolean
status = True
While (True)
If (number = 0) Then
Exit While
Else
temp = number Mod 10
If (temp > 1) Then
status = False
Exit While
End If
number = number / 10
End If
End While
Return status
End Function
Then:
Dim isBinary as Boolean
isBinary = binary(Convert.ToInt32(TextBox1.Text))

Related

How can I solve my "sub main was not found" problem?

Module PrimePairs
Public Function IsPrime(n As Long) As Boolean
Console.WriteLine("Please enter the value: ")
n = Console.ReadLine()
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
Public Function PrimePairs(ByVal n As Long, ByVal n2 As Long) As Integer
Dim count As Integer = 0
Console.ReadLine()
If n Mod 2 = 0 Then
For i = 1 To (n / 2) + 1
n2 = n - i
If IsPrime(i) And IsPrime(n2) = True Then
count += 1
End If
Next
Else
n2 = n - 2
If IsPrime(n2) = True Then
count = +1
End If
End If
Console.WriteLine("The result is:", count)
Return n
End Function
End Module
I want my code to calculate how many prime number twins can write the input I gave.
The problem is that your project actually does not contain a Sub Main(), as the error states.
You defined two functions in the Module Program, but console applications need a predefined entry point, which usually is the Main method.
The compiler is telling you that your project is not valid because it didn't find any entry point.
Just add a Sub Main() to get your project working, then call your functions from that method.
Example:
Option Strict On
Module Program
Sub Main(args As String())
Console.WriteLine("Please enter the value: ")
Dim input As String = Console.ReadLine()
Dim number As Long
If Long.TryParse(input, number) Then // More about this function in the answer below
Dim prime As Boolean = IsPrime(number)
If prime Then
Console.WriteLine(number & " is prime.")
Else
Console.WriteLine(number & " is not prime.")
End If
End If
Console.ReadLine()
End Sub
Function IsPrime(n As Long) As Boolean
n = Math.Abs(n) ' Allows to consider negative prime numbers
If n < 2 Then ' Disallows -1, 0, 1
Return False
End If
Dim i As Long = 2
i = 2
While i < n ' Note that for n = 2 we don't enter the loop and thus return True.
If n Mod i = 0 Then
Return False
End If
i += 1
End While
Return True
End Function
End Module
Also, I suggest you to enable Option Strict On as I added at the beginning of file. This prevents the compiler from doing implicit casts and forces you to explicitly declare your variables.
E.g., your line of code
n = Console.ReadLine()
is not valid with Option Strict On, because n is supposed to be a long, but Console.ReadLine() returns a string.
If you are a beginner, this will allow you to better understand how programming works and will help you to avoid errors - take good habits from the beginning, you can thank me later ;)
That's why I changed your code withLong.TryParse(input, number): this function returns true if provided input can be cast (=converted) to a long, and assigns the casted value to number variable.
There's a lot more I'd like to suggest you, but I would go off-topic.

vb.net readline or readkey don't want to stop my program

my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance
Dim count As Integer
Dim first(5) As Integer
Dim temp As Integer
Dim answer As String
Sub Main()
Do
Console.WriteLine("Please enter your first number")
first(0) = Console.ReadLine
Console.WriteLine("Please enter your second number")
first(1) = Console.ReadLine
Console.WriteLine("Please enter your third number")
first(2) = Console.ReadLine
Console.WriteLine("Please enter your fourth number")
first(3) = Console.ReadLine
Console.WriteLine("Please enter your fifth number")
first(4) = Console.ReadLine
Console.WriteLine("Please enter your sixth number")
first(5) = Console.ReadLine
randomnumber()
Console.WriteLine("do you want to continue?")
answer = Console.ReadLine
Loop Until (answer = "n" Or answer = "No")
Console.ReadKey()
End Sub
Sub randomnumber()
Dim r As New List(Of Integer)
Dim rg As New Random
Dim rn As Integer
Dim arraywinner(5) As Integer
Do
rn = rg.Next(1, 40)
If Not r.Contains(rn) Then
r.Add(rn)
End If
Loop Until r.Count = 6
'store bane random value in array'
arraywinner(0) = r(0)
arraywinner(1) = r(1)
arraywinner(2) = r(2)
arraywinner(3) = r(3)
arraywinner(4) = r(4)
arraywinner(5) = r(5)
'print random numbers
count = 0
While count <= 5
Console.WriteLine("the randoms numbers are : " & arraywinner(count))
count = count + 1
End While
'look for the amount of number
temp = 0
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If arraywinner(count1) = first(count2) Then
temp = temp + 1
End If
Next
Next
If temp = 1 Or temp = 0 Then
Console.WriteLine("You have got " & temp & " number")
Else
Console.WriteLine("You have got " & temp & " numbers")
End If
money(temp)
End Sub
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
You have two problems in money():
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...
I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random
Public Sub Main()
'keep variables with as narrow a scope as possible
Dim answer As String = Nothing
'This line initializes and array of strings called words
Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
Dim WinnersChosen(5) As Integer
Do
'To shorten your code use a For loop
For index = 0 To 5
Console.WriteLine($"Please enter your {words(index)} number")
WinnersChosen(index) = CInt(Console.ReadLine)
Next
Dim RandomWinners = GetRandomWinners()
Console.WriteLine("The random winners are:")
For Each i As Integer In RandomWinners
Console.WriteLine(i)
Next
Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)
If WinnersCount = 1 Then
Console.WriteLine($"You have guessed {WinnersCount} number")
Else
Console.WriteLine($"You have guessed {WinnersCount} numbers")
End If
Dim Winnings = Money(WinnersCount)
'The formatting :N0 will add the commas to the number
Console.WriteLine($"Your winnings are {Winnings:N0}")
Console.WriteLine("do you want to continue? y/n")
answer = Console.ReadLine.ToLower
Loop Until answer = "n"
Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
Dim RandomWinners As New List(Of Integer)
Dim rn As Integer
'Good use of .Contains and good logic in Loop Until
Do
rn = rg.Next(1, 40)
If Not RandomWinners.Contains(rn) Then
RandomWinners.Add(rn)
End If
Loop Until RandomWinners.Count = 6
Return RandomWinners
End Function
Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
Dim temp As Integer
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If r(count1) = WinnersChosen(count2) Then
temp = temp + 1
End If
Next
Next
Return temp
End Function
Private Function Money(Count As Integer) As Integer
'A Select Case reads a little cleaner
Select Case Count
Case 3
Return 120
Case 4
Return 500
Case 5
Return 10000
Case 6
Return 1000000
Case Else
Return 0
End Select
End Function
End Module

Identifying a function when reading in Visual Basic

I'm having trouble idetifying what this does? my confusion relates to the "end for" does this mean the function would end the 'for' loop if the value is false?
example data in Array can [2,4,5] Val 3, Result would be false and end the loop or?
Thanks in advance.
Function YetToName (data As Integer(), val As Integer) As Boolean
Dim i As Integer
For i = 0 To data.Length - 1
If data(i) = val Then
Return True
End If
End For
Return False
End Function
The code snippet you have provided is not valid vb.net code.
"Exit For" is used to break out of a For-Next loop before the loop completes.
A For-Next Loop must, by definition, have a "Next" statement to be valid. The code could be rewritten as...
Function YetToName(data As Integer(), val As Integer) As Boolean
Dim i As Integer
Dim ReturnValue As Boolean = False
For i = 0 To data.Length - 1
If data(i) = val Then
ReturnValue = True
Exit For
End If
Next
Return ReturnValue
End Function

VB perfect function

What is wrong with this perfect number function?
The method is supposed to decide whether the input number is/is not a perfect number. The answer is supposed to be all the perfect numbers from 1 to the input.
For example: 1 - 100 the answer would be 6 and 28
Public Function isPerfect(myInput As Integer) As Boolean
endCounter = myInput \ 2
sum = 1
For perfectCounter As Integer = 2 To endCounter
If myInput Mod perfectCounter = 0 Then
sum += perfectCounter
If sum = myInput Then
Return True
End If
End If
Next
Return False
End Function
Private Sub btnPerfect_Click(sender As Object, e As EventArgs) Handles btnPerfect.Click
input = Convert.ToInt32(txtNumber.Text)
msg = "The perfect numbers between 1 and " & input & " are : "
For inputCounter As Integer = 0 To input
If isPerfect(inputCounter) = True Then
msg += inputCounter & " "
End If
Next
MsgBox(msg, , "Perfect Number")
txtNumber.Focus()
txtNumber.Text = Nothing
End Sub
You have at least a couple of problems:
You are validating the perfect number inside the loop, before you've even finished summing the divisors.
For instance...
If sum = myInput Then
Return True
End If
The above should be checked after the loop.
More importantly, because you are setting endCounter to myInput \ 2, you are not summing all the divisors. Maybe you did this as an optimization. But if so, you forgot something along the way.
A quick fix is to change the endCounter assignment to:
endCounter = myInput - 1
Also, to avoid getting back 1 as a valid perfect number, I would initialize sum to 0, and would start the loop normally at 1 instead of 2.
So your function could look something like:
Public Function isPerfect(myInput As Integer) As Boolean
Dim endCounter As Integer = myInput - 1
Dim sum As Integer = 0
For perfectCounter As Integer = 1 To endCounter
If myInput Mod perfectCounter = 0 Then
sum += perfectCounter
End If
Next
Return sum = myInput
End Function
I'm sure you could optimize this further if you want to.
(*) Consider turning on Option Explicit as well.
Here is the correct implementation of isPerfect:
Public Function isPerfect(myInput As Integer) As Boolean
dim Sum as Integer = 1
For i as Integer = 2 To myInput / 2
If myInput Mod i = 0 Then Sum = Sum + i
Next
Return Sum = myInput
End Function

Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used

I keep getting a error and because of this my code wont work. The error is "Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used". I can't get rid of this error. I'm new to programming, can anyone help?
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
End If
Else
MessageBox.Show("Value has to be a number")
End If
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
txtNumberOfScores.Text = CStr(UpperSub)
End Function
A Function is designed to return a result, using the Return keyword. Your Function does not have a Return statement. Since none of the possible code paths (determined by branching on the If statements as well as the flow from beginning to end) return a value, you're getting this part of the error message: "Function 'DisplayArray' doesn't return a value on all code paths."
The second part of the error message means that if you tried to assign the return value of the Function to a variable, like this:
Dim result As String = DisplayArray()
You'd get a null value, as nothing is returned from the function.
The simplest solution is to change from a Function to a Sub. Subs in VB.NET do not return a value. So change
Private Function DisplayArray() As String
To
Private Sub DisplayArray()
And
End Function
To
End Sub
Note that the As String() in the Function declaration says this method will return a value that is a String, and the Sub has no return value (again, because it doesn't return a value).
To make this a Function that returns a value, you'll have to return at least one value from the method. Here's an example:
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
Return String.Empty
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Return String.Empty
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
Return CStr(UpperSub)
End If
Else
MessageBox.Show("Value has to be a number")
Return String.Empty
End If
End Function
Essentially, if the validation fails, an empty string is returned. If the validation passes, the rest of the code is executed and the string value of UpperSub is returned.
You could then assign it to the TextBox like this:
txtNumberOfScores.Text = DisplayArray()
The above is a simple example based on your posted code, intended to show you how to return values from a Function. Adjust it to fit your needs (or use a Sub instead). Given that you want to update the display of the txtDisplay with the array and txtNumberOfScores as well you should do fine with a Sub.