سؤال

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top