Reputation: 109
I am having a problem with my loop and I realise there is probably a slight adjustment needs to be made to get this working the right way but I just cant see what that is! I have included the code below:
final int SIZE = 6;
//array to store user numbers
int [] userNumbers = new int[SIZE];
boolean found = false;
int pos = 0;
boolean bonus = false;
int lottCount = 0;
while (pos<SIZE)
{
System.out.println("enter your numbers");
userNumbers[pos]=keyboard.nextInt();
pos++;
}
for (int count: userNumbers)
{
System.out.println(count);
}
for (int loop = 0; loop <numbers.length; loop++ )
{
for (int loopOther = 0; loopOther < SIZE; loopOther++)
{
if (userNumbers[loop] == numbers[loopOther])
lottCount++;
}
if (userNumbers[loop] == bonusBall)
{
bonus = true;
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}
}
System.out.println("You have matched " + lottCount + " numbers");
The ouput looks like this:
15
16
17
18
19
43
You have not won at this time
You have not won at this time
You have not won at this time
You have not won at this time
You have not won at this time
You have matched 1 numbers the bonus ball43
You have matched 1 numbers
I only want the program to inform me of each condition once. can anyone help me with this? Thanks in advance
Upvotes: 0
Views: 143
Reputation: 109547
for (int loop = 0; loop <numbers.length; loop++ )
{
for (int loopOther = 0; loopOther < SIZE; loopOther++)
{
if (userNumbers[loop] == numbers[loopOther])
lottCount++;
}
if (userNumbers[loop] == bonusBall)
{
bonus = true;
}
}
if (bonus)
{
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}
Or shorter:
for (int number : numbers)
{
for (int userNumber : userNumbers)
{
if (userNumber == number)
lottCount++;
}
if (userNumber == bonusBall)
{
bonus = true;
}
}
if (bonus)
{
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}
Upvotes: 2