简体   繁体   中英

Do… while loop in Java

Can anybody tell me what is going wrong here?? I'm getting caught in an infinite loop.

do{
    System.out.print("cards["+pickRandom+"] is:"+cards[pickRandom]);
    pickRandom = (int)(Math.random() * 52);  //pick a new random card
    System.out.print(" so now cards["+pickRandom+"] is:"+cards[pickRandom]);
    if (cards[pickRandom] != 0) {  //if it's not 0, then assign it
        System.out.print("cards["+pickRandom+"] is not 0: "+cards[pickRandom]);
        shuffled[k]=cards[pickRandom];
        System.out.print(" shuffled["+k+"]:"+shuffled[k]);
        cards[pickRandom]=0;
        //System.out.println("For card "+k+ ": "+ shuffled[k] +" was found on pick number "+count);
    } 
    else{System.out.println("cards["+ pickRandom+ " was:" +cards[pickRandom]);}
}while (cards[pickRandom]==0);

I am trying to pick a random card that is not ==0. If it is ==0, I want the loop to pick another card

Your if block is guaranteed to change any cards[pickRandom] that's non-zero to 0. And doing this will mean that your while condition is always true.

So in essence, this is your code's logic:

int x = 1;
do { 
   x = // some random value
   if (x != 0) {
      x = 0;
   }
while (x == 0);

Solution: don't do this. Use some other way to end your loop. For more detailed help, please explain your code and its goals in more detail.


A possible solution to your problem: set your array value to zero after the while loop:

  do {
     pickRandom = (int) (Math.random() * 52);
     if (cards[pickRandom] != 0) {
        shuffled[k] = cards[pickRandom];

        //  cards[pickRandom] = 0; // *** don't do this here ***

     } else {
        // not sure what you want here
     }
  } while (cards[pickRandom] != 0);

  cards[pickRandom] = 0;  // **** do it here! ****

The reason being, at that point, you'll know that a correct card has been picked. One problem though -- consider testing to make sure that all values in cards are not 0.

Better solution: use an ArrayList of Integers, shuffle them with Collections.shuffle() , and then simply remove the 0th item from the loop each time, as long as size() > 0.

You are setting your cards[pickRandom] to 0 in each case-

cards[cards[pickRandom]=0;  

And after that you check condition in while loop -

while (cards[pickRandom]==0);

So in the condition in while loop always evaluated to true and that's why the loop continues for ever without stopping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM