[英]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
. 我需要访问两个String variables
suit
和rank
,然后在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: 我会做这样的事情:
Card
class which has a suit and a rank 创建一个具有西装和等级的Card
类 Deck
class to store "cards remaining in the deck", starting with one of each card (or more) 创建一个Deck
类来存储“卡片组中剩余的卡片”,从每张卡片中的一张(或更多张)开始 Player
class which has a collection of cards as the hand 创建一个具有一组手牌的Player
类 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.) 创建一个PokerGame
类(或类似的类)作为入口点-这是main
的类。(我认为将它放在Deck
中没有多大意义。) Define the variables outside of the foor-loop, like here: 在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.