Please help I am stuck. I have an ArrayList filled with elements and I want to be able to run it through a loop assigning each element a unique variable name. I know how to use the loop and cycle through the list but giving each one a unique name has got me stumped. Not sure what to do.
It isn't possible to dynamically create variable names, so you aren't going to be able to do what you describe. If you tell us why you want to do that we might be able to suggest an alternative.
For instance, if you just need to be able to associate strings with your elements you can use a HashMap to do that.
Thanks for the quick responses. With this code I was going to draw the balls and then run the through the while loop. The while loop does not recognize my variable and I was going to give each ball a unique name.
OK, then you definitely don't need a bunch of different variable names.
The reason your ball variable isn't recognised is because it's defined within the scope of the for loop. If you want to use it later you need to declare it in a wider scope.
But let me ask this - in your while loop, which ball are you intending to bounce? Surely you want all of them to bounce, don't you? In which case you need another for loop within the while loop that iterates over all the balls. Then you'll have a ball variable you can use. And notice that this wouldn't be possible if you had a bunch of separate variables. Putting your balls in a list is exactly what you need here.
If, on the other hand, you only want a single ball to bounce, then you want a single variable referencing that particular ball. But I'm guessing that's not the intention.
May I ask what gui Framework you are using?
If you are using Swing/JavaFx/Swt you won't see anything at all (well at least not what you want to see) even if you fix that one bug!
Manuel Petermann wrote:May I ask what gui Framework you are using?
If you are using Swing/JavaFx/Swt you won't see anything at all (well at least not what you want to see) even if you fix that one bug!
I am working within the BlueJ development environment.
My favorite is a chocolate cupcake with white frosting and tiny ad sprinkles.
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth