What's Wrong With my logic in this Vb program? - vb.net

I'm new to visual basic and I just started taking classes on it at school. I was given an assignment to write an app that tells if an input in a textbox is a Prime Number Or Not.
I have written this code snippet in Visual Studio:
Public Class PrimeNumberApp
Public Sub CheckButton_Click(sender As Object, e As EventArgs) Handles CheckButton.Click
Dim x, y As Integer
x = Val(PrimeTextBox.Text)
For y = 2 To (x - 1)
Select Case x
Case Is = (33), (77), (99)
MsgBox("Its not a prime number, try a different number!")
Exit Sub
End Select
If x Mod y = 0 Then
MsgBox("Its not a prime number, try a different number!")
Exit Sub
Else
MsgBox("Its a prime number, you're golden!")
Exit Sub
End If
Next
Select Case x
Case Is <= 0
MsgBox("I'm only accepting values above 0. :p")
Exit Sub
End Select
End Sub
I have this code snippet displaying a Message Box telling whether the input by the user is a prime number or not with the help of the Mod operator in visual basic.
If you go through the code carefully, you'll notice I had to separately create more or less escape statements for the number 33, 77 and 99.
I had to do this cause every time I typed either of those three numbers, I'd get the result that the number is a prime number which is incorrect since they're all divisible by numbers apart from themselves. Without getting things mixed up, the program displays other prime and non-prime numbers with the right Message Box, just those three.
I had spent hours trying to figure out what I had done wrong before I added the lines below to put myself out of vb misery, lol.
Select Case x
Case Is = (33), (77), (99)
MsgBox("Its not a prime number, try a different number!")
Exit Sub
End Select
But doing this isn't healthy if I really want to be awesome at coding. So here's my question, how do I get this program fixed to display the right message box when any integer is typed in the text box. Thanks.

Your code doesn't seem to work at all. It seems to always say that every number is a prime number. You loop through every possible divisor and in that loop you test to see if the input is evenly divisible by the current divisor. That part makes sense. The problem, though is that you always immediately exit the loop after the first iteration regardless of the result of the test. Pay close attention to this code from inside your loop:
If x Mod y = 0 Then
MsgBox("Its not a prime number, try a different number!")
Exit Sub
Else
MsgBox("Its a prime number, you're golden!")
Exit Sub
End If
If we remove all of the spurious details, you can tell that the logic is flawed:
If MyTest = True Then
Exit Sub
Else
Exit Sub
End If
As you can see, no matter what the result of the test is, it's always going to exit the loop. Therefore, the loop will never progress beyond the first iteration. In order to make it continue testing every possible divisor, you need to remove the Exit Sub statements and just keep track of the result in a variable. For instance, something like this:
Dim isPrime As Boolean = True
For y = 2 To x - 1
If XIsEvenlyDivisibleByY Then
isPrime = False
Exit For
End If
Next
If isPrime Then
' ...
Else
' ...
End If
Notice that once the first evenly divisible divisor is found, I have it Exit For. There's no point in searching any further since one is enough to make it not prime.
For what it's worth, you should use Integer.TryParse rather than Val and you should use MessageBox.Show rather than MsgBox. Val and MsgBox are old VB6 style functions. It's preferable to use the newer .NET-only versions.

here is an example of how to find prime numbers, for example up to 100, using 2 loops to check every single number in a given range. In this case I started by 2 because as you know 2 is the smallest of the prime numbers.
Dim i As Integer = 2, j As Integer = 2
For i = 2 To 100
For j = 2 To (i / j)
If i Mod j = 0 Then
Exit For
End If
Next
If (j > (i / j)) Then
Console.WriteLine("{0} is prime", i)
End If
Next

Related

Even Odd numbers using Nested For Next Loop VBA

How do I create a For-Next loop determining whether the numbers listed are even or odd
You can try something like this:
Dim i As Integer
For i = 1 To 6
If i mod 2 = 0 Then
'i is even
Else
'i is odd
End If
Next i

How Do I Count When Numbers Do Not Show Up

I have numbers from 1 to 25, four numbers will show up daily. I need to put a +1 on each of the four numbers and need to put a -1 on each of the 21 numbers didn't show up.
The four numbers that come up daily will be inputted in four different text boxes. The count being positive or negative needs to go on 25 separate text boxes labeled 1 thru 25.
I have tried "if textbox <> number, then count -= 1" but I get a count of -4 because it doesn't see the number in any of the four text boxes.
I only need a daily count not a textbox count. Sorry I don't have any code started and would greatly appreciate if someone can point me in the right direction. I'm doing this on Visual Studio 2012.
Thank you all for responding. Here is some code I've started but the count is not correct. My four input text boxes are in GroupBox2. Four numbers from 1 to 25 will draw daily like a lottery. The four numbers drawn will have a value of +1 each all others -1. I need to find the age of each number 1 thru 25. If a number has a +3 then that means that number has drawn 3 consecutive days. If a number has a -15 then that means that number has not drawn for the past 15 days.
Dim tb As New TextBox
Dim ctrl As Control
Dim Counter As Integer
For Each ctrl In GroupBox2.Controls
tb = ctrl
If tb.Text = 1 Then
Counter += 1
ElseIf tb.Text <> 1 Then
Counter -= 1
TextBox464.Text = Counter
End If
If tb.Text = 2 Then
Counter += 1
ElseIf tb.Text <> 2 Then
Counter -= 1
TextBox463.Text = Counter
End If
If tb.Text = 3 Then
Counter += 1
ElseIf tb.Text <> 3 Then
Counter -= 1
TextBox462.Text = Counter
End If
If tb.Text = 4 Then
Counter += 1
ElseIf tb.Text <> 4 Then
Counter -= 1
TextBox461.Text = Counter
End If
Next
We will need more information about how your going to approach it to be able to help you further, but as for your problem with this If Textbox <> number Then count -= 1 you can use something like this since your only going to be having numbers on the textboxes If Cint(Textbox.Text) <> number then count -= 1 since your using just Textbox its attempting to evaluate it as a control and not the property that your looking for, you need to read from its .Text Property, However since its evaluated as a String and not an Integer it will throw an error exception, thats why the Cint() is included (This may also be used to convert it to integer Ctype(number, Integer) Not sure if there is an execution speed difference or not, however Cint() is a faster way of writing it.) it will try and convert the String into an Integer and when its converted into an integer it can be evaluated like one using <>. No one is going to write a whole solution out for you, but while you attempt to create it yourself and more information can be added we are more than happy to help you with problems along the way.

Do Until Loop InputBox infinitely loops

I am creating a probability macro where user enters number of players in a card game. If I enter string (ex, Joe), non-integer(ex, 15.67), or integer less than 0 (ex, -25), the InputBox should loop. However, integers greater than 0 should terminate the loop. (I have to force kill Excel to stop the InputBox regardless of user input.)
I want the InputBox to close / Exit Sub once an integer greater than 0 is entered. What am I doing wrong here?
Sub GenerateCards()
Players = InputBox("How many players? Please enter an integer.")
Do Until TypeName(Players) = "Integer" And Players > 0 ' why does this loop even if both conditions are met (ex, Players=5?)
Players = InputBox("How many players? Please enter an integer.")
Loop
End Sub
InputBox() always returns a string, so TypeName() will always return "String".
But you can test if the string that's returned is an integer. First, you can use IsNumeric() to test if the string is a numeric value. Then, you can safely cast it to a Double or an Integer. In fact, you can cast it to both and then compare them against each other. If they're the same, you've got an integer value. For example:
Sub GenerateCards()
Do
Players = InputBox("How many players? Please enter an integer.")
If IsNumeric(Players) Then
If CDbl(Players) = CLng(Players) And Players > 0 Then
' Integer > 0 entered. Exit loop...
Exit Do
End If
End If
Loop
End Sub

Visual Basic - How to sort highest and lowest number of a series?

****I don't necessarily want the code to fix this problem, I would just like if someone would be able to explain to me why this is happening or what I could have done better to solve this problem.****
I have a homework assignment where I need to print out the highest and lowest number of a series.I am currently able to print out the highest and lowest numbers but if all of the numbers entered are positive, then it displays my lowest number as 0, and same if all the entered numbers are negative.
So if someone would be able to explain how to solve this, without necessarily giving away the answer, it would be greatly appreciated!
Here is my code:
Module Module1
'This is going to have the user enter a series of numbers,
'Once the user is finished have them enter '-99' to end the series,
'then it is going to return largest and smallest number
Sub Main()
NumSeries()
End Sub
'This is going to get the series from the users
Sub NumSeries()
Dim largeNum As Integer = 0
Dim smallNum As Integer = 0
Dim userNum As Integer = 0
Dim largeTemp As Integer = 0
Dim smallTemp As Integer = 0
Console.WriteLine("Please enter a series of positive and negative numbers")
Console.WriteLine("Then type '-99' to end the series")
Console.WriteLine()
While (userNum <> -99)
Console.Write("Enter num: ")
userNum = Console.ReadLine()
If (userNum > largeTemp) Then
largeTemp = userNum
largeNum = largeTemp
ElseIf (userNum < smallTemp And userNum <> -99) Then
smallTemp = userNum
smallNum = smallTemp
End If
End While
Console.WriteLine("The largest number is " & largeNum)
Console.WriteLine("The smallest number is " & smallNum)
End Sub
End Module
Two points:
You don't need the variables largeTemp and smallTemp.
(The answer to your question) You should initialize largeNum to a very small number, and smallNum to a very large number. For example, if smallNum is set to zero at the beginning of the program, only numbers smaller than zero will replace it. To find an error like this, you should trace through the program either by hand or with a debugger and see what happens at each step. It would be a good idea to do this now so you'll understand the problem. (Alternatively, as Idle-Mind pointed out, you can initialize largeNum and smallNum to the first item in the list.)
Don't use any sentinel values at all. Simply declare a Boolean variable so you know if you the value retrieved is the very first one or not:
Dim FirstEntry As Boolean = True
If it is, then set both largeNum and smallNum to that value. Now just compare each additional entered value with those stored values to see if they are bigger or smaller than the previously known extreme.
A few things you should improve upon:
You can remove the temp variables. They don't serve any other purpose other than unnecessarily consuming memory and CPU time.
You should initialize your min and max variables with highest and lowest possible values respectively. If you think larger than integer values should be allowed, change the type to Long
Dim largeNum As Integer = Integer.MinValue
Dim smallNum As Integer = Integer.MaxValue
Remove the ElseIf. Use two If statements instead. This is so that both variables will be set with the very first input itself.
If (userNum > largeNum) Then largeNum = userNum
If (userNum < smallNum) Then smallNum = userNum

Random number macro does not return desired value

I have created a simple module that is meant to do following:
generate random number between 0 and 999;
if number is lower than 500, assign value "lower", otherwise "higher"
write the random number and assigned value in cells A1 and B1
repeat the process 100,000 times.
Problem is, it returns assigned value "lower" even if the number is higher than or equal to 500, i.e., all assigned values, 100,000 of them, are "lower"!
I'd appreciate if someone can check where I'm going wrong with this code; I'm not an expert in VBA, but I thought I could do this myself... :\
Sub MacroRanNum()
Dim RunNum As Integer
Dim Outcome As String
For i = 1 To 100000
Randomize
RanNum = Int((999 - 0 + 1) * Rnd + 0)
If RunNum < 500 Then
Outcome = "Lower"
ElseIf RunNum >= 500 Then
Outcome = "Higher"
Else
Outcome = "Error!"
End If
Sheets("podatak").Cells(i, 1) = RanNum
Sheets("podatak").Cells(i, 2) = Outcome
Next i
End Sub
Your variable name is RanNum but you check for RunNum
OPTION EXPLICIT could help to avoid such problems.
You are mixing your variable names. You define and check against RunNum but your random value and your display value are RanNum. You are never testing against the value you randomly generated.