0

我的循环有问题,我意识到可能需要稍作调整才能使其正常工作,但我看不出那是什么!我已包含以下代码:

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

我只希望程序将每种情况通知我一次。谁能帮我这个?提前致谢

4

1 回答 1

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");
     }
于 2013-08-20T07:39:45.930 回答