[英]Is there any way to access a String variable inside of a for loop?
我需要訪問兩個String variables
suit
和rank
,然后在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.