So I am writing a program where somebody draws cards from a deck. So I wrote a while loop that loops through and checks to see if there are over 4 of the randomly created card drawn, and if there is, change the card.
here is my code:
String card = (int)Math.ceil(Math.random() * 13) + " ";
String[] used2 = used.split(" ");
//used is a String like "12 3 7 8 4 ... # etc" such that it is all the previously drawn cards.
boolean checking = true;
boolean isIn = false;
int in = 0;
int check = 0;
while(checking){
for(int q = 0; q < used2.length; q++){
check += 1;
if(card.equals(used2[q] + " ")){
in += 1;
if(in == 4){
System.out.println(check); //debugging line
check += 1;
card = (int)Math.ceil(Math.random() * 13) + " ";
card_val = (int)Math.ceil(Math.random() * 13);
isIn = true;
in = 0;
break;
}
}
}
if(isIn){
//will execute if there is 4 of the cards already drawn so the while loop continues with a different card
checking = true;
}
else{
//breaks out of while loop because the card can be drawn
checking = false;
}
}
used += card;
Now this runs, but when I put it inside a for loop and set it to run like 40 times, about 2/3 times it creates an of infinite loop.
I discovered that the infinite loop is only created if the if(in == 4) statement comes out to be true.
Why is this? I have been debugging since last night and I cannot figure this out.
if-elsestatement:checking = isIn;isIntotruein that block, which meanscheckingwill never get set tofalse.(int)Math.ceil(Math.random() * 13) + " ". I suspect your reason for" "is to convert the int to String, however you can only do+""which makes the code simpler afterwards..+" "?