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("請(qǐng)輸入玩家序號(hào)"); int newnum = input.nextInt(); System.out.println("請(qǐng)輸入玩家名字"); String newname = input.next(); Cardclass newcd = (Cardclass)newcard.get(n); ? // 第二次執(zhí)行時(shí)候會(huì)提示越界 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++; } }}問題在注釋那句 ?剛剛學(xué)不是很懂 - -!
1 回答
已采納

sxian_wang
TA貢獻(xiàn)16條經(jīng)驗(yàn) 獲得超8個(gè)贊
不要亂用繼承!繼承一定是子類和父類之間存在“是不是”的關(guān)系,即子類一定是父類的一種,即子集。一個(gè)人能是撲克牌的一種嗎?所以你的代碼問題就出現(xiàn)在了這里,main函數(shù)實(shí)例化people的時(shí)候。因?yàn)槟愕膒eople都是繼承的Card類,而newCard這個(gè)List又被你設(shè)置成static變成了共享變量。所以你在main函數(shù)里面,執(zhí)行cd.add()后,第一次運(yùn)行的時(shí)候newCard是正常的;當(dāng)你運(yùn)行到實(shí)例化people一行的時(shí)候,因?yàn)閜eople繼承的是Card,它會(huì)調(diào)用父類的無(wú)參構(gòu)造器,你看看你父類的無(wú)參構(gòu)造是啥玩意?初始化newCard。所以你第二次運(yùn)行的時(shí)候newCard變成空的了,自然會(huì)報(bào)ArrayIndexOutOfBounds異常。
至于修正的辦法很多種,我就不提供了,你自己動(dòng)動(dòng)腦子吧~
添加回答
舉報(bào)
0/150
提交
取消