我的循环有问题,我意识到可能需要进行一些调整才能使其正常工作,但我不知道那是什么!我已经包含以下代码:
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");
输出看起来像这样:
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
我只希望程序一次通知我每个条件。谁能帮我这个?提前致谢
答案 0 :(得分:2)
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");
}
或更短:
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");
}