Even Odd numbers using Nested For Next Loop VBA - 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

Related

Changing end integer of a loop within said loop

I am working on some code and I am trying to modify the end integer of a loop within said loop (as said in the title)
So it would look like this
dim x as integer
For i=0 to x
if (some conditions) then
x=x+1
End if
Next
However it doesn't seem to work, it looks like the loop is working with a static value of x and not a dynamic value.
Is there a way to update the end integer of the loop without using an exit for and starting the loop all over?
Thanks
You can use a While loop.
dim x as integer
Dim i as Integer = 0
While i <= x
if (some conditions) then
x=x+1
End if
End While

InvalidArgument=Value of ' ' is not valid for 'index' (' ' inside number)

This is my first question. I can't solve this error for 2 weeks.
In order to solve the problem signed up.
This is my vb code.
Try
For i As Integer = 0 To ListBox1.Items.Count - 1 Step 1
For j As Integer = 0 To ListBox2.Items.Count - 1 Step 1
If ListBox1.Items(i).ToString().Equals(ListBox2.Items(j).ToString()) = True Then
ListBox1.Items.RemoveAt(i)
End If
Next
Next
Catch ex As Exception
MsgBox("LOAD ERROR: " + ex.Message, vbCritical, "ERROR")
End Try
error :
InvalidArgument=Value of '20' is not valid for 'index'(' ' is varient.)
Project has no problems except for this error
Try this:
Dim items = ListBox1.Items.Where(Function(item) ListBox2.Items.Contains(item)).ToList()
For Each item in items
ListBox1.Remove(item)
Next
When I run your code, I receive a different exception, argument out of range...and that is caused by deleting items from an indexed collection while you're iterating through it. For example, let's say listbox1 has 10 items in it. If you find item number 1 in listbox2 and delete it, now you only have 9 items left in listbox1. The problem is, when you entered your loop, you told it to loop 10 items, and it will still try to do that. At some point, if any items are deleted, this loop will throw an exception...so you will need to change that sooner or later. To mitigate this, step through the collection that you'll be deleting items from backward like this:
For i As Integer = ListBox1.Items.Count - 1 to 0 Step -1
When I run the code with the change shown above, it works as intended and removes the duplicate items from listbox1. Unfortunately, I was unable to reproduce your invalid argument exception. It's odd to see that because usually that exception likes to pop up when using listviews, not listboxes. Perhaps you can edit your post and add a screenshot of the data in your listboxes so it's easier for other people to troubleshoot.
As you remove items from ListBox1 the total item count will decrease (obviously), however the For loop does not respect that. A For loop will only have the right side of To set once, which is done prior to the first iteration.
What you're currently doing is actually equal to this:
Dim a As Integer = ListBox1.Items.Count - 1
For i As Integer = 0 To a Step 1
Dim b As Integer = ListBox2.Items.Count - 1
For j As Integer = 0 To b Step 1
...
Next
Next
The fix for this is simple; create a variable that holds how many items you have removed, then, in an If-statement, check if i is more or equal to the current item count subtracted with how many item's you've removed. If so, exit the loop.
Dim ItemsRemoved As Integer = 0
For i As Integer = 0 To ListBox1.Items.Count - 1 Step 1
If i >= ListBox1.Items.Count - ItemsRemoved Then Exit For
For j As Integer = 0 To ListBox2.Items.Count - 1 Step 1
If ListBox1.Items(i).ToString().Equals(ListBox2.Items(j).ToString()) = True Then
ListBox1.Items.RemoveAt(i)
End If
Next
Next
For future reference you should also always remove/comment out the Try/Catch-statement so you can see where the error occurs and get more detail about it.
The point of my answer is that when you iterating any collection, you should NOT try to modify this collection. In for-loops you run into such trouble. But you can iterate using while-loop with no issues
Try
Dim index As Integer = 0
While index < ListBox1.Items.Count '!! this code based on fact that ListBox1 item Count changes
For j As Integer = 0 To ListBox2.Items.Count - 1 ' <- this is ok because ListBox2 doesn't chage
If string.Equals(ListBox1.Items(index).ToString(), ListBox2.Items(j).ToString()) Then
ListBox1.Items.RemoveAt(index)
Continue While ' no index increase here because if you remove item N, next item become item N
End If
Next
index += 1
End While
Catch ex As Exception
MsgBox("LOAD ERROR: " + ex.Message, vbCritical, "ERROR")
End Try
This is good example of how things actually work. And it shows few techniques
I just selected Build-->Clean solution and it cleaned out the bad elements. This occurred as a result of adding and deleting menu items, without deleting the subroutines of the deleted menu items. As soon as I cleaned the solution, and then ran the project, the error was gone.

VB.Net - Remove empty items in ListBox

I want to remove empty items from my listbox that looks something like this:
book1
book2
book3
book4
book5
And so on..
I have tried this code:
Dim i As Integer = 0
Do While (ListBox1.Items.Count) - 1 >= i
If String.IsNullOrEmpty(ListBox1.Items(i)) Then
ListBox1.Items.Remove(ListBox1.Items(i))
i -= 1
End If
i += 1
Loop
And i don't know why it's not working.
You can use any type of loop for any purpose but each type is best suited to certain situations and a Do While loop is a poor choice in this case. The best option in this case is to use a For loop and count backwards:
For i = ListBox1.Items.Count - 1 To 0 Step -1
If String.IsNullOrEmpty(CStr(ListBox1.Items(i))) Then
ListBox1.Items.RemoveAt(i)
End If
Next

What's Wrong With my logic in this Vb program?

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

Nested loop with same variable

Is that possible for me to do nested loop in VB with same counter
The code is somehow like this
For a As Integer = 1 to Console.ReadLine
For a = 1 to a
Console.WriteLine("*")
Next
Console.WriteLine()
Next
The program is designed for drawing a triangle of * with just a single variable at all
VB just disallow me to use a in nested loop again
Error: ...Variable 'a' is alreay used by a independent loop.
I have my own usage, can only use 1 variable.
What changing the second FOR loop to a WHILE loop?
For a As Integer = 1 to Console.ReadLine
Do While a <=5
Console.WriteLine("Line: " & a)
Exit Do
Loop
Next
Here's a different idea. You may consider splitting your integer variable into 2 parts 16-bit parts, keep user's input in the upper 16-bits, and current iteration value in the lower 16-bits (you'll need to use WHILE instead of FOR).
In fact, what you need is to start your inner counter by the value of a, if I've understand. And what you are doing is create another loop inside starting by 1.
For a As Integer = 1 to Console.ReadLine
For b As Integer = a to 5
Console.WriteLine("Line: " & a)
Next
Next
You cannot declare another variable with the same name in the same scope. But the inner loop is in the same scope as the outer loop. That's why you get that compiler error.
You can use a different name:
Dim i As Int32
If Int32.TryParse(Console.ReadLine, i) AndAlso i > 0 Then
For a As Integer = 1 To i
For aa = 1 To i
Console.WriteLine("Line: {0} {1}", a, aa)
Next
Next
End If
To draw a triangle, as you describe, you need two variables, like this:
For a As Integer = 1 to Console.ReadLine
For b As Integer = 1 to a
Console.Write("*")
Next
Console.WriteLine()
Next
If you used the same variable in the inner loop, the inner loop would change the value of the variable, which in most cases would not be what you want, and in all cases would be incredibly confusing. For that reason, VB forces you to use a different iterator in each nested For loop.