List序列越界问题

import java.util.*; 

class Cardclass{

public String ID;

public String color;

public Cardclass(String ID , String color){

this.ID = ID;

this.color = color;

}

}

class Card{

static List<Cardclass> newcard;

public Card(){

this.newcard = new ArrayList<Cardclass>();

}

public void add(){

int i;

int j;

int n=0;

String[] IDs=new String[13];

IDs[0] = "A";

IDs[1] = "2";

IDs[2] = "3";

IDs[3] = "4";

IDs[4] = "5";

IDs[5] = "6";

IDs[6] = "7";

IDs[7] = "8";

IDs[8] = "9";

IDs[9] = "10";

IDs[10] = "J";

IDs[11] = "Q";

IDs[12] = "K";

String[] color=new String[4];

color[0] = "Black";

color[1] = "Red";

color[2] = "Plum";

color[3] = "Square";

for(i = 0 ; i < 13 ; i++){

for(j = 0 ; j < 4 ; j++){

Cardclass cc = new Cardclass(IDs[i],color[j]);

newcard.add(cc); 

Cardclass outPut = (Cardclass)newcard.get(n);

System.out.println(outPut.ID + "  " + outPut.color);

n++;

}

}

}

}

class people extends Card{

public int Num;

public String Name;

public String id;

public String color;

public people(int x , String y ,String newID , String newcolor){

Num = x;

Name = y;

System.out.println("1");

id = newID;

color = newcolor;

}

}

public class tp extends Card{

public static void main(String[] args){

int i;

int j;

int n=0;

Card cd = new Card();

cd.add();

System.out.println("*********************");

Scanner input = new Scanner(System.in);

for(i = 0 ; i < 2 ;i++){

System.out.println("请输入玩家序号");

int newnum = input.nextInt();

System.out.println("请输入玩家名字");

String newname = input.next();

Cardclass newcd = (Cardclass)newcard.get(n);   // 第二次执行时候会提示越界

String newID = newcd.ID; 

String newcolor = newcd.color;

people newpeople = new people(newnum , newname , newID , newcolor);

System.out.println(newpeople.Num+" "+newpeople.Name+" "+newpeople.id+" "+newpeople.color);

n++;

}

}

}

问题在注释那句  刚刚学不是很懂 - -!

Js_Ly
浏览 1881回答 1
1回答

sxian_wang

不要乱用继承!继承一定是子类和父类之间存在“是不是”的关系,即子类一定是父类的一种,即子集。一个人能是扑克牌的一种吗?所以你的代码问题就出现在了这里,main函数实例化people的时候。因为你的people都是继承的Card类,而newCard这个List又被你设置成static变成了共享变量。所以你在main函数里面,执行cd.add()后,第一次运行的时候newCard是正常的;当你运行到实例化people一行的时候,因为people继承的是Card,它会调用父类的无参构造器,你看看你父类的无参构造是啥玩意?初始化newCard。所以你第二次运行的时候newCard变成空的了,自然会报ArrayIndexOutOfBounds异常。至于修正的办法很多种,我就不提供了,你自己动动脑子吧~
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java