繁体   English   中英

有什么办法可以在for循环中访问String变量吗?

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

我需要访问两个String variables suitrank ,然后在for loop之外使用它们。 这是可能吗?

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
    }
}

如果您想发牌,那么在我看来您需要收集-毕竟,一个玩家拥有多张卡。

我认为您需要退后一步,而不是继续当前的代码。 我会做这样的事情:

  • 为西装定义一个枚举
  • 为等级定义一个枚举
  • 创建一个具有西装和等级的Card
  • 创建一个Deck类来存储“卡片组中剩余的卡片”,从每张卡片中的一张(或更多张)开始
  • 创建一个具有一组手牌的Player
  • 创建一个PokerGame类(或类似的类)作为入口点-这是main的类。(我认为将它放在Deck中没有多大意义。)
  • 从卡组到玩家,随便你想要多少张牌。

在foor循环之外定义变量,如下所示:

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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