为 N 名玩家生成一手牌(每手五张牌)
问题:编写一个程序 Deal.java,它采用命令行参数 N 并从洗好的牌中打印 N 手扑克牌(每手五张牌),并用空行分隔。
我所拥有的:
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank =
{
"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"
};
// initialize cards in a deck
String[] deck = new String[suit.length * rank.length];
for (int i = 0; i < rank.length; i++)
for (int j = 0; j < suit.length; j++)
deck[rank.length*i + j] = rank[i] + " of " + suit[j];
// shuffle deck
int d = deck.length;
for (int i = 0; i < d; i++)
{
int r = i + (int) (Math.random() * (d-i));
String temp = deck[r];
deck[r] = deck[i];
deck[i] = temp;
}
// repeat for N number of people
for (int t = 0; t < N; t++)
{
// print 5 random cards
for (int i = 0; i < 5; i++)
System.out.print(deck[i] + " ");
System.out.println();
}
}
有人能告诉我我在这里做错了什么吗?我收到错误 ArrayIndexOutOfBoundsExceptions,不知道为什么。这是我书本上的习题,不是家庭作业。
Problem: Write a program Deal.java that takes an command-line argument N and prints N poker hands (five cards each) from a shuffled deck, separated by blank lines.
What I have:
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank =
{
"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"
};
// initialize cards in a deck
String[] deck = new String[suit.length * rank.length];
for (int i = 0; i < rank.length; i++)
for (int j = 0; j < suit.length; j++)
deck[rank.length*i + j] = rank[i] + " of " + suit[j];
// shuffle deck
int d = deck.length;
for (int i = 0; i < d; i++)
{
int r = i + (int) (Math.random() * (d-i));
String temp = deck[r];
deck[r] = deck[i];
deck[i] = temp;
}
// repeat for N number of people
for (int t = 0; t < N; t++)
{
// print 5 random cards
for (int i = 0; i < 5; i++)
System.out.print(deck[i] + " ");
System.out.println();
}
}
Can anybody tell me what I'm doing wrong here? I'm getting an error ArrayIndexOutOfBoundsExceptions, not sure why. This is a problem out of an exercise set from my book, not homework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您在这一行遇到数组索引越界异常:
您的意思一定是:
I assume you're getting an array-index-out-of-bounds exception on this line:
where you must have meant this:
除了 ruakh 发现的索引错误之外,您还打印了同一手牌
N
次:要打印不同的手牌,请使用另一个索引变量,
In addition to the index error spotted by ruakh, you are printing out the same hand
N
times:To print out different hands, use another index variable,
我看不出问题出在哪里,似乎工作正常,尝试提供一些进一步的细节。
您应该改进的是:
检查开始时的参数设置是否正确:
I can't see what's the problem seems to work ok, try to give some further details.
Something you should improve is:
Check the parameter is set at the beginning properly: