1

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.

Feyisayo Sonubi
  • 1,052
  • 5
  • 15
  • 27
  • 1
    Your question is really "how do I tell if a number is prime"? You have a lot of superfluous information here. And as this is a common question, there are plenty of answers floating around. Like this one: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime – Jon B Apr 16 '14 at 20:01
  • Hi, Thanks for the reference. Like I said, I'm still new to Visual Basic, I checked out the link above and found out the codes there are in C#, I need a way to fix my program in visual basic. – Feyisayo Sonubi Apr 16 '14 at 20:29
  • You'll need to post the modified code so I can see it. – Steven Doggart Apr 17 '14 at 00:51
  • @FeyisayoSonubi you'll find that there is a lot of great sample code out there written in C#. It's worth having a basic understanding of C# syntax to be able to read code and translate it to your language of choice. – Jon B Apr 17 '14 at 13:00

2 Answers2

1

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.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
  • Wow, thanks for the elaboration, I removed all the `Exit Sub` statements in my code and added a `End For` statement but still got the message box that the numbers I mentioned earlier are prime numbers. What else can be wrong please? – Feyisayo Sonubi Apr 16 '14 at 21:03
  • @FeyisayoSonubi - Use the debugger to step through your code line by line and you will find the source of your problem. Plus it's a good opportunity to learn to use the debugger. – Chris Dunaway Apr 17 '14 at 12:44
1

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
  • Thank you so much guys, lol, I've got one more thing I'd like to ask, how do I have the event of a button control in my code also be initiated on the press of a key? So rather than have the user pressing a button in my program to get a result everytime, the user just needs to press the `Enter` key that will have the same effect as pressing the button – Feyisayo Sonubi Apr 18 '14 at 12:17
  • it's very simple. Go to the form properties on the right and select the property "accept button" and choose the button you want to trigger when you press enter. There's also a cancel property on the form to trigger a button when escape is pressed. As a good practice in this forum, don't forget to vote an useful answer :) –  Apr 18 '14 at 18:24
  • Thank you so much Fernando, I would have voted up your answer but I can't cause I don't have a reputation more than 15 yet. :( ...The suggestion you gave worked fine and did like I expected :D ...but what if I wanted the statements in my button's event handler to be called on the press of say, the "B" key on my keyboard, how do I get that done? – Feyisayo Sonubi Apr 18 '14 at 19:46
  • the easier way to avoid code is on the button properties. Go to the text property(of the button you want to launch) and place an ampersand before the letter you want(b in this case) and then once you press Alt+letter on the form the button will trigger, Ex-> &button1 –  Apr 18 '14 at 20:46
  • we all need to study, I'll recommend you to read some tutorials or books for beginners, it;s up to you which one you choose. here is my blog, I have books in pdf format about VB, C#, c++, java and more, take a look http://computertechnologydocumentation.blogspot.com/ –  Apr 18 '14 at 20:51