这里的代码很适合一次处理两张牌,这是我正在进行的纸牌游戏的主要设置。我遇到的问题是我无法抓住程序并在到达套牌结束之前让它停止。基本上应该发生的是,当牌组被设置为52张牌时,每次按下输入时,它将一次抽取两张牌。一旦它落到最后两张牌(我希望由j == 1
表示),if语句就会捕获它并运行一组单独的代码,打印最后两张牌然后说"你没有牌了#34;出于某种原因,无论我如何设置if语句,它都不会进行评估,程序到达套牌的末尾并给出错误
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at Game.main(Game.java:65)
不知道如何才能让它在太晚之前赶上列表的大小。
ArrayList<String> deckList = new ArrayList<String>(Arrays.asList(deck));//Changing Array with card contents into an ArrayList
while (deckComplete == false) { //While loop for dealing cards
for (int j = deckList.size(); j > 0; j--) {
// System.out.println("Hit enter to be dealt a card!");
String readString = scanner.nextLine(); //Set variable "readString" to user input
if (readString.equals("")) { //If user input equals "enter"...
Collections.shuffle(deckList, new Random());
if (j == 1) { //If program gets to last card...
deckComplete = true; //Set desk complete to true
System.out.println(deckList.get(0));
System.out.println(deckList.get(1));//Print last card
System.out.println("You are out of cards!"); //Print "You are out of cards"
break; //Stop loop
}
System.out.println(deckList.get(0)); //Print first card. Error code points here.
deckList.remove(0); //Remove card
System.out.println(deckList.get(0)); //Print next card
deckList.remove(0); //remove card
}
}
答案 0 :(得分:2)
你初始化j = deckList.size()
但j每次迭代只减1,而你每次实际拿2张牌。 j需要递减2:
ArrayList<String> deckList = new ArrayList<String>(Arrays.asList(deck));//Changing Array with card contents into an ArrayList
while (deckComplete == false) { //While loop for dealing cards
for (int j = deckList.size()-1; j > 0; j-=2) {
// System.out.println("Hit enter to be dealt a card!");
String readString = scanner.nextLine(); //Set variable "readString" to user input
if (readString.equals("")) { //If user input equals "enter"...
Collections.shuffle(deckList, new Random());
if (j == 1) { //If program gets to last card...
deckComplete = true; //Set desk complete to true
System.out.println(deckList.get(0));
System.out.println(deckList.get(1));//Print last card
System.out.println("You are out of cards!"); //Print "You are out of cards"
break; //Stop loop
}
System.out.println(deckList.get(0)); //Print first card
deckList.remove(0); //Remove card
System.out.println(deckList.get(0)); //Print next card
deckList.remove(0); //remove card
}
}