Reputation: 83
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
Upvotes: 1
Views: 429
Reputation: 285440
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.
Upvotes: 2
Reputation: 11173
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.
Upvotes: 1