调用空方法
我需要在调用另一个方法之前调用 void 方法。
我有这个方法
public void shuffle() {
various = new Random();
currentCard = 0;
currentTotal1 = 0;
currentTotal2 = 0;
for (int first = 0; first < deckOfCards.length; first++) {
int second = various.nextInt(number_cards);
Card temp = deckOfCards[first];
deckOfCards[first] = deckOfCards[second];
deckOfCards[second] = temp;
}
}
,在另一个类中我有:
public class GameRules {
final deck myDeckOfCards = new deck();
myDeckOfCards.shuffle(); //error here
// first
public ImageIcon GameRules1() {
return myDeckOfCards.giveCardPlayer1().getImage();
}
基本问题是我需要在展示牌之前在牌堆中进行洗牌。如果没有洗牌方法,纸牌的顺序是连续的
你知道吗?如果我将该方法放在 public ImageIcon GameRules1()
中不会给出错误,但我需要在游戏前洗牌所有卡片,而不是在每个给出卡片方法之前洗牌。
谢谢
I need to invoke a void method before call another method.
I have this method
public void shuffle() {
various = new Random();
currentCard = 0;
currentTotal1 = 0;
currentTotal2 = 0;
for (int first = 0; first < deckOfCards.length; first++) {
int second = various.nextInt(number_cards);
Card temp = deckOfCards[first];
deckOfCards[first] = deckOfCards[second];
deckOfCards[second] = temp;
}
}
And in another class I have:
public class GameRules {
final deck myDeckOfCards = new deck();
myDeckOfCards.shuffle(); //error here
// first
public ImageIcon GameRules1() {
return myDeckOfCards.giveCardPlayer1().getImage();
}
The basic problem is that I need to do shuffle in the deck of cards before show a card. Without shuffle method the order of cards is sequential
Any idea? If I put the method inside public ImageIcon GameRules1()
doesn't give error, but I need shuffle all cards before game, no before each give card method.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将该调用放在类的构造函数内:
构造函数是您为对象执行初始化任务的地方。
另外,您确实不应该有一个名为
GameRules()
的方法来返回ImageIcon
。您应该重命名该方法getImage
或类似的名称。然后,当您使用构造函数创建一个 GameRules 并对其调用 getImage 时,牌组将被洗牌。示例:
查看 Java 教程,了解有关为类编写构造函数的良好教程.
You should place that call inside your constructor for the class:
The constructor is the place where you do initialization tasks for your objects.
Also, you really shouldn't have a method called
GameRules()
that returns anImageIcon
. You should rename that methodgetImage
or something like that. Then, when you create aGameRules
with the consturctor and callgetImage
on it, the deck will be shuffled.Example:
Check out the Java tutorials for a good tutorial on writing constructors for your classes.
要么按照建议使用构造函数,或者,如果在某些时候您有多个构造函数,您可能希望将它们通用的代码移至初始值设定项:
但是,正如注释中指出的,使用构造函数更好,链接如果需要的话构造函数。事实证明,实例初始值设定项最适合在匿名类中使用。
Either use a constructor as suggested, or, if at some point you have multiple constructors, you may wish to move the code that is common to them to an initializer:
But, as pointed out in the comments, using a constructor is better, chaining constructors if necessary. It turns out that instance initializers are best used in anonymous classes.
为什么不直接在
deck
构造函数中调用shuffle
方法呢?Why don't you call
shuffle
method indeck
constructor directly?