我想寫一個方法來顯示一個遊戲的套牌。 我98初始化的Array
元素
測試數組是否爲空JUNIT
private int [] cards = new int[98];
我還創建了一個get和set方法
public int[] getCards() {
return cards;
}
和
public void setCards(final int... cards) {
this.cards = cards;
}
我寫的方法稱爲drawCard
。如果我使用這種方法,它應該從Array
中刪除第一個元素並將其返回。
public int drawCard() throws IndexOutOfBoundsException {
if (getCards().length == 0) {
throw new IndexOutOfBoundsException("No Cards Left!");
}
setCards(ArrayUtils.removeElement(getCards(), 0));
return getCards()[0];
}
然後我寫了JUnit測試。 測試應刪除所有98個元素,然後數組應爲空== 0
。 但測試總是停在1
@Test
public void testDrawCard() {
Deck deck = new Deck();
assertThat(deck.getCards().length).isEqualTo(98);
for(int x = 98; x >= 0; x--){
deck.drawCard();
}
assertThat(deck.getCards().length).isEqualTo(0);
}
錯誤消息:
java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35)
35 =返回行
at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
是否有人知道什麼是錯?
你從98循環到!包容性! 0. – Androbin
您正試圖刪除99個元素。 – Androbin
只需將> =更改爲簡單的> – Androbin