简体   繁体   中英

Is there any way to access a String variable inside of a for loop?

I need to access the two String variables suit and rank , then use them outside of the for loop . Is this at all possible?

public class Deck {    

    public static void main(String[] args) {

        int deck[] = new int[52];
        String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
        String ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

        for(int i = 0; i < deck.length; i++) deck[i] = i;

        for(int i = 0; i < deck.length; i++) {
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }
        // randomizes the deck
        for(int i = 1; i < deck.length; i++) {
            String suit = suits[deck[i] / 13];  // I want to access these two Strings
            String rank = ranks[deck[i] % 13];  // here
            System.out.println(rank + "\t" + suit);

        }
        // and use them here
        // I'm trying to make a poker game but need to use those two to deal a hand
    }
}

If you're trying to deal a hand then it seems to me you need a collection - after all, a player holds multiple cards.

I think you need to take a step back, rather than continuing with your current code. I'd do it something like this:

  • Define one enum for suits
  • Define one enum for ranks
  • Create a Card class which has a suit and a rank
  • Create a Deck class to store "cards remaining in the deck", starting with one of each card (or more)
  • Create a Player class which has a collection of cards as the hand
  • Create a PokerGame class (or something similar) as the entry point - that's the class which has main in. (It doesn't make much sense for it to be in Deck , in my opinion.)
  • Deal from the deck to the player, as many cards as you want.

Define the variables outside of the foor-loop, like here:

String suit;
String rank;
for(int i = 1; i < deck.length; i++) {
    suit = suits[deck[i] / 13];  // I want to access these two Strings
    rank = ranks[deck[i] % 13];  // here
    System.out.println(rank + "\t" + suit);

    }
    // and use them here

    // I'm trying to make a poker game but need to use those two to deal a hand
}

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