javaif-statementrandomcontainsretain

how would i match the number of correct guesses?


I wanted to make a program like a lottery where winning numbers are randomly generated.

I used (guessednumbers.containsAll(winningnumbers) if the user guessed all the 6 numbers.

If the user only got to guess 5 digits, what method should I use to count the 5 correct numbers from the random generated ones?

The code would be:

System.out.println("The winning numbers were: " + winningNumbers);
System.out.println("Your numbers are: " + guessedNumbers);

guessedNumbers.retainAll(winningNumbers);
System.out.println("Your matched numbers are: " + guessedNumbers);

if (guessednumbers.containsAll(winningNumbers)); {
    System.out.println("Jackpot!");

}
else if (the supposed code if 5 digits were guessed correctly)
    System.out.println("You won a consolation prize!"); }

class are java.util.List, java.util.Random and java.util.ArrayList;.

data types are all integer.


Solution

  • Since you already called guessednumbers.retainAll(winningNumbers) the amount of correctly guessed numbers is just the size of guessedNumbers.

    if (guessedNumbers.size() == 5)
        System.out.println("You have guessed exactly 5 numbers correct.");