拋出我試圖做一個小程序,創建一個撲克牌我想不通。所有的代碼編譯,但是當我嘗試運行測試類,它說:爲什麼ArrayIndexOutOfBoundsException異常這裏
異常線程「main」 java.lang.ArrayIndexOutOfBoundsException:52
在cardDeck.giveValue(cardDeck.java:23 )
在CardTest.main(CardTest.java:6)
我只用了幾個星期的java,所以我不知道到底是哪裏的問題,或如何解決它。我會很感激任何幫助。
卡類:
public class Card {
private int value;
private String name;
private String suit;
public void setValue(int v){
value = v;
}
public int getValue(){
return value;
}
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void setSuit(String s){
suit = s;
}
public String getSuit(){
return suit;
}
}
張牌類:
public class cardDeck {
int [] values = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
String[] names = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "King", "Queen", "Jack", "Ace"};
String[] suits = {"Clubs", "Spades", "Hearts", "Diamonds"};
public Card[] giveName (Card[] d){
int j = 0;
while(j < 52){
for(String k: names){
d[j] = new Card();
d[j].setName(k);
j++;
}
}
return d;
}
public Card[] giveValue(Card[] e){
int a = 0;
while(a < 52){
for(int m: values){
if((e[a].getName().equals("King")) || (e[a].getName().equals("Ten")) || (e[a].getName().equals("Queen")) || (e[a].getName().equals("Jack"))){
e[a].setValue(10);
a++;
}else if(e[a].getName().equals("Ace")){
e[a].setValue(11);
a++;
}else{
e[a].setValue(m);
a++;
}
}
}
return e;
}
public Card[] giveSuit(Card[] f){
int b = 0;
while(b < 52){
for(String l:suits){
f[b].setSuit(l);
b++;
}
}
return f;
}
}
Tester類:
class CardTest {
public static void main(String[] args){
Card[] deck = new Card[52];
cardDeck playingCards = new cardDeck();
playingCards.giveName(deck);
playingCards.giveValue(deck);
playingCards.giveSuit(deck);
for(int q = 0; q < 52; q++){
System.out.println("A "+deck[q].getName()+ " of " +deck[q].getSuit()+ " " +deck[q].getValue());
}
}
}
爲什麼你用'while'循環用手動計數器代替'for'循環? – chrylis
哪一行是23?你使用調試器時看到了什麼? –