0

所以我正在写一个Lottery类和一个类来演示这个Lottery类。我已经完成了工作并且可以编译,但是当我运行它时,我得到了

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4  
at LotteryDemo.main(LotteryDemo.java:21)

这是我的代码,任何帮助将不胜感激!

Lottery班级:

    import java.util.Random;


import java.util.Scanner;

   public class Lottery
   {


  int NUM_DIGITS = 5;   
  int[] lotteryNumbers = new int[4];




  public Lottery(){
     Random rand = new Random();
     lotteryNumbers[0] = rand.nextInt(10);
     lotteryNumbers[1] = rand.nextInt(10);
     lotteryNumbers[2] = rand.nextInt(10);
     lotteryNumbers[3] = rand.nextInt(10);
     lotteryNumbers[4] = rand.nextInt(10);
     getLotteryNums();

  }


  public int numIntsInCommon(int[] picks){
     int inCommon = 0;

     for (int counter = 0; counter < 5; counter++)
     {
        for (int index = 0; index < 5; index++)
        {
           if (lotteryNumbers[counter] == picks[index])
              inCommon++;
           return inCommon;
        }
        return inCommon;
     }

     return inCommon;
  }

  public String getLotteryNums(){
     return lotteryNumbers[0] + ", " + lotteryNumbers[1] + ", " + 
                    lotteryNumbers[2] + ", " + lotteryNumbers[3] + ", " +
                    lotteryNumbers[4];
  }




}

LotteryDemo班级:

    import java.util.*;


   public class LotteryDemo
   {
  public static void main(String[] args)
  {

        Scanner input = new Scanner(System.in);
     int[] userNumbers = new int[4];

     System.out.println("Please supply your lottery picks. Choose unique numbers between 0 and 9.");
     System.out.print("Enter digit 1: ");
        userNumbers[0] = input.nextInt();
        System.out.print("Enter digit 2: ");
        userNumbers[1] = input.nextInt();
        System.out.print("Enter digit 3: ");
        userNumbers[2] = input.nextInt();
        System.out.print("Enter digit 4: ");
        userNumbers[3] = input.nextInt();
        System.out.print("Enter digit 5: ");
        userNumbers[4] = input.nextInt();


    Lottery lottery = new Lottery();


    System.out.print("Lottery Numbers: " + lottery.getLotteryNums());
  System.out.print("Number of matching digits: " + lottery.numIntsInCommon(userNumbers));
    if(lottery.numIntsInCommon(userNumbers) == 5)
        System.out.print("All 5 match! You have hit the jackpot!");
  }


}
4

3 回答 3

1
int[] lotteryNumbers = new int[4];

这意味着该数组有 4 个元素或lotteryNumbers[0]....lotteryNumbers[3]

从而lotteryNumbers[4] = rand.nextInt(10);会导致上述异常。

userNumbers与导致异常的 in main类似。

int[] userNumbers = new int[4];
...
userNumbers[4] = input.nextInt(); // java.lang.ArrayIndexOutOfBoundsException
于 2013-01-12T07:57:49.327 回答
0

您分配数组,new int[4]这意味着它有 4 个元素,编号为 0 到 3。当您访问索引为 4 的元素时,它超出了范围。

于 2013-01-12T07:58:16.003 回答
0

Java中的数组具有如下实例化:

type[] name = new type[size]
                       ^

大小表示数组中的索引数。如您所知,数组从零开始,因此:

int[] userNumbers = new int[4]

制作一个数组:

[ ][ ][ ][ ]
 0  1  2  3

userNumbers[4]因此不存在。您需要userNumber[5]为五个索引创建。

于 2013-01-12T08:09:37.633 回答