だから私は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!");
}
}