1

Here's my code:

public static void main(String[] args) {

    int lotteryNumbers[] = new int[5];
    int playersNumbers[] = new int[5];
    int winNum = 0;


    Scanner in = new Scanner(System.in);
    Random r = new Random();
    // array med 5 heltal

    //skapa en for loop som fyller upp arrrayen
    //med slumpade tal från klassen Random
    for (int i = 0; i < lotteryNumbers.length; i++) {
        lotteryNumbers[i] = 0 + r.nextInt(9);
        System.out.print(lotteryNumbers[i] + "\t");

    }
    System.out.println();

    for (int i = 0; i < playersNumbers.length; i++) {
        //System.out.println("Var god ange ett nummer mellan 0-9: ");
        //playersNumbers[i]=in.nextInt();
        playersNumbers[i] = 0 + r.nextInt(9);

    }
    for (int i = 0; i < playersNumbers.length; i++) {

        System.out.print(playersNumbers[i] + "\t");

    }
    System.out.println();

    if (lotteryNumbers[0]==playersNumbers[0])
         winNum++;
         if (lotteryNumbers[1]==playersNumbers[1])
              winNum++;
              if (lotteryNumbers[2]==playersNumbers[2])
                   winNum++;
                   if (lotteryNumbers[3]==playersNumbers[3])
                        winNum++;
                        if (lotteryNumbers[4]==playersNumbers[4])
                            winNum++;

     System.out.println("You have " + winNum + " winning numbers");

}

}

I need to compare the numbers index to index. As you can see I have 5 if statements. I was wondering if I can do this with a loop instead?

I already tried to do as this:

for (int i = 0; i < lotteryNumbers.length; i++) {

        for (int j = 0; j < playersNumbers.length; j++) {

       if (lotteryNumbers[i] == playersNumbers[j]) {
                winNum++;

            }
        }
    }

But this compares every index with every index, not just index to index. I want to know how to write a loop for compare index to index?

1
  • Use one loop, not two. Commented Feb 12, 2015 at 7:53

2 Answers 2

2

Only use one loop. That way the same index can be used across the two arrays.

for (int i = 0; i < lotteryNumbers.length; i++) {
    if (lotteryNumbers[i] == playersNumbers[i]) {
            winNum++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're working too hard. :-) Just one loop, not two, and use the same index variable with both arrays:

for (int i = 0; i < lotteryNumbers.length; i++) {
    if (lotteryNumbers[i] == playersNumbers[i]) {
        winNum++;
    }
}

3 Comments

I realized I could do it with enhanced for loop
@TapaniYrjölä: The enhanced for loop doesn't help you here.
I realized that when I tried. Your answer is the right one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.