Go Down

Topic: For loop, try again (Read 690 times) previous topic - next topic


Im using a for loop to change an amount of items in an array. But it is changing them randomly, and I cant have to change the same one twice, so i need a dynamic way to keep from choosing the same number twice since I dont know how many of them will be changed at a time. Luckily I can easily see if it has already been changed by seeing if it equals 1. So i need to know how to "try again", or in other words, add another loop to a for loop.

Code: [Select]

for(int x = 1;x<=NumberToChange;x++){        //For how many items need to be changed
tempVal = random(0, arraySize)               //tempVal = a random items number
if (myArray[tempVal] == 1){                  //if the array item is already set to 1:
                                             //TRY AGAIN
else{                                        //if the array item is NOT already set to 1:
myArray[tempVal] = 1;                        //set the array items to 1

where it says //TRY AGAIN i need to tell it to attempt that loop again. Can i simply use x--?



Inside the for loop, you need a while loop.

Code: [Select]
for(int x = 1;x<=NumberToChange;x++)
   boolean stillNeedToChange = true;
      tempVal = random(0, arraySize);   //tempVal = a random item's index
      if (myArray[tempVal] == 0)
         myArray[tempVal] = 1;
         stillNeedToChange = false;
The art of getting good answers lies in asking good questions.


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131