String length help! How to I limit the length of my string? I want my shuffled d
ID: 660168 • Letter: S
Question
String length help!
How to I limit the length of my string? I want my shuffled deck to only disply 13 cards out of 52. here is my code below:
public class game extends Application {
private Card[] theDeck;
private int nextCard;
public game() {
theDeck = new Card[ Card.NUM_SUITS * Card.CARDS_IN_SUIT ];
for( int i = 0; i < theDeck.length; i++ ) {
theDeck[ i ] = new Card( i );
}
nextCard = 0;
}
public Card draw() {
Card retVal = null;
if ( !isEmpty() ) {
retVal = theDeck[ nextCard ];
nextCard = nextCard + 1;
}
return retVal;
}
public Card[] draw( int n ) {
Card[] hand = null;
if ( !isEmpty() ) {
hand = new Card[ Math.min( n, cardsInDeck() ) ];
for ( int i = 0; i < hand.length; i++ ) {
hand[ i ] = draw();
}
}
return hand;
}
public void shuffle() {
Random rng = new Random();
for ( int cur = 0; cur < theDeck.length; cur++ ) {
int target = rng.nextInt( theDeck.length );
Card tmp = theDeck[ target ];
theDeck[ target ] = theDeck[ cur ];
theDeck[ cur ] = tmp;
}
}
public int cardsInDeck() {
return theDeck.length - nextCard;
}
public boolean isEmpty() {
return cardsInDeck() == 0;
}
public String toString() {
String retVal = "";
if ( !isEmpty() ) {
StringBuffer cardsLeft = new StringBuffer( "[" );
for ( int i = nextCard; i < theDeck.length; i++ ) {
cardsLeft.append( " " );
cardsLeft.append( theDeck[ i ].toString() );
}
cardsLeft.append( " ]" );
retVal = cardsLeft.toString();
}
return retVal;
}
public static void main(String[] args){
game myDeck = new game();
myDeck = new game();
while ( !myDeck.isEmpty() ) {
myDeck.shuffle();
Card[] hand = myDeck.draw( 4 );
for ( int i = 0; i < hand.length; i++ ) {
String fileName = "file:./playing_cards_images/" +hand[i] +".jpg";
System.out.print(fileName+ " ");}
I want to change in the for statement under the main method to limit the hand.length to only showing 13 of it's combination. What should I put in to do that? Thank you very much!
Explanation / Answer
put a counter in for statement just before System.out.print in main method
initialize counter with 0
zin main do like this:
String fileName.........
counter++;
if (counter>13)
break;
System.out.print.......