簡體   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