当我使用-1退出循环时,为什么会得到ArrayIndexOutOfBounds?

时间:2015-03-19 19:06:27

标签: java

我正在制作卡片和甲板课程。我已经做到了这一点,它要求用户从1-52输入数字,这将显示一张卡片,并输出-1以退出循环。一旦循环结束,它将显示所有52张牌。最后,我希望我的程序达到用户输入他们想要处理多少张牌的程度,程序将处理。在我到达那里之前,我在输入-1后不断收到ArrayIndexOutOfBounds错误。这是我的代码,

我的卡类(保持片段简短):

public class Cards
    {
        private Face face;
        private Suit suit;

        public Cards ()
        {
            face = Face.ACE;
            suit = Suit.SPADES;
        }

        public Cards (int n)
        {

            face = Face.values() [n % 13];
            suit = Suit.values() [n % 4];
        }
    }

我的司机:

public class driver
{
    public static void main(String []args)
    {
        Scanner kb = new Scanner(System.in);        //For int
        Scanner kb2 = new Scanner(System.in);       //For strings
        int iNum=0;             //holds users input for non-negative number
        String strDeck;         //variable to catch showDeck

        do
        {
            System.out.println ("Enter a number between 1-52, enter -1 to stop.");

            iNum = kb.nextInt();
            if (iNum <= -1)
            {
                strDeck = showDeck();
            }
            Cards userCard = new Cards(iNum);
            System.out.println ("Your card is " + userCard.toString());
        }

        while (iNum >= -1);
        {
            System.out.println("Press ENTER to continue ");
            kb2.nextLine();
        }

很抱歉间距问题,特别是我得到的错误是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at cards.Cards.<init>(Cards.java:44)
at cards.driver.main(driver.java:28)

1 个答案:

答案 0 :(得分:1)

因为,正如您的代码所说,当用户输入-1时,它继续执行new Card(iNum),即new Card(-1)(就在if语句之后)。

也许你打算将这一点放在else语句中,或者在break调用后你也可以showDeck()退出循环。


顺便提一下,请记住你的换行符。现在,您的代码格式化方式可能有些令人困惑。你有:

do {
   ...
}

while (iNum >= 1);
{
   ...
}

但是whiledo循环的一部分,而不是跟随它的{ ... }范围的一部分(注意分号所在的位置)。格式化有点误导,很容易导致错误。你可能希望这样格式化:

do {
   ...
} while (iNum >= 1);

{
   ...
}

虽然这一切似乎都是一个错字,但我怀疑你的意思是将while条件应用于“按ENTER继续”位而不是。