问答详情
源自:7-1 简易扑克牌游戏

java在不同类中调用一个集合,发牌方法调用扑克牌类里的list为0???

--------首先是扑克牌类的list集合, ----------------------------------------------------------

package cardGame;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


public class ShuffleAllCards {

public List<String> cards;

public ShuffleAllCards(){

this.cards = new ArrayList<String>();

}

/**

* 生成所有52张牌

* */

public void CardsCreate(){

System.out.println("-----------游戏开始!-----------");

//通过遍历得到所有52张牌.

String[] number = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; 

String[] color = {"黑桃","红桃","梅花","方块"};

for(int i=0;i<number.length;i++){

for (int j = 0; j < color.length; j++) {

//第一个是 黑桃A, 然后 红桃A, 

String OneCard = color[j]+number[i];

//每一次都加到List里,list是有序的.

cards.add(OneCard);

}

}

if(cards.size() == 52){

System.out.println("-----------生成扑克牌成功-------");

}

}

/**

* 打乱所有52张牌的顺序

* */

public void ShuffleCards(){

System.out.println("-----------开始洗牌-----------");

Collections.shuffle(cards);

System.out.println(cards.size());  //-----------------------这里输出的是52,是对的--------------------

System.out.println("-----------洗牌结束-----------");

}

}

---然后在游戏类里的发牌方法里调用上面的list集合,给玩家的手牌, 想先看看list的大小, 居然是0,但是在扑克牌类里是52呀...-------------

package cardGame;


import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;


public class LetUsPlay {

Scanner console = new Scanner(System.in);

//定义一个玩家List

public List<Players> players;

public LetUsPlay() {

//初始化玩家List

players = new ArrayList<Players>();

}


/**

* 创建玩家方法

* */

public void CreatePlayers(){

System.out.println("-----------登记玩家信息-----------");

System.out.println("一共有几位玩家呢?");

int playerCounter = console.nextInt();

for(int i=0;i<playerCounter;i++){

//确定一共有几个玩家

System.out.println("请输入第"+(i+1)+"位玩家ID: ");

int playerId = console.nextInt();

System.out.println("请输入第"+(i+1)+"位玩家姓名: ");

String playerName = console.next();

Players player = new Players(playerId,playerName);

players.add(player);

}

for (Players players : players) {

System.out.println(players.name);

}

}


/**

* 为玩家发牌,之前扑克牌已经打乱顺序了

* */

public void GiveCards(){

Players player = new Players();

ShuffleAllCards giveCards = new ShuffleAllCards();

System.out.println(giveCards.cards.size());  //-----------这里输出的list的size是0???应该是52呀??

}

}


提问者:CarlGK 2018-08-20 09:46

个回答

  • 喵喵_喵
    2018-08-26 02:45:59

     new ShuffleAllCards(); 调用了构造方法

    public ShuffleAllCards(){

    this.cards = new ArrayList<String>();

    }

    构造方法里已经将cards重新new了。

    ShuffleAllCards 类的引用应该在main函数里执行

    你这里直接用cards就好了,反正是成员变量