0

这是我到目前为止所拥有的。我最终进入了输入数组数字的无限循环,但是,就数字而言,它继续正确循环

static void ticketNumberArray(){

    int number = 1;             //which of the six numbers you need from the ticket
    int ticketCount = 1;            //which ticket (out of 20) you are currently on

    while(ticketCount<21){      //sentinel controlled while loop, will continue until the twentieth ticket is entered

         System.out.println("Please type number " +number+ " of ticket number " +ticketCount+ ".");     //asks for the numbers of the ticket your currently on
         Scanner keyboard = new Scanner(System.in);             //initiates a scanner variable
         int ticketNumber = keyboard.nextInt();             //assigns user input to the double variable ticketNumber and initializes as a double

         tickets[ticketCount-1][number-1]=ticketNumber;     //assigns user input into a 2-d array

         number++;                                      //Sentinel variable

         if(number==7){                                     //loop that controls the ticket count, every 6 numbers ='s one ticket
          ticketCount++;
          number=1;
         }
     }
}
4

4 回答 4

1

它不是无穷无尽的,它只需要20 * 6 = 120 times输入用户结束循环......

于 2012-04-23T01:55:21.420 回答
1

这是次要的,但仅供将来参考,当您分配 ticketNumber 时,它是一个 int,但您的评论是双倍的。你的意思可能是int,但如果你把它们混在一起可能会导致问题。

于 2012-04-23T01:32:37.837 回答
0

考虑将您的方法重写ticketNumberArray()为以下内容:

static void ticketNumberArray()
{
   for (int ticketCount = 1; ticketCount <= 20; ticketCount++)
   {
      for (int numberCount = 1; numberCount <= 6; numberCount++)
      {
         System.out.println("Please enter a number for ticket number " + ticketCount + ".");

         Scanner keyboard = new Scanner(System.in);

         int number = keyboard.nextInt();

         tickets[ticketCount - 1][numberCount - 1] = number;
      }
   }
}

通过这种方式,您的意图更加清晰,并且您的循环实际上确实终止了,这一点更加明显。

于 2012-04-23T02:02:22.697 回答
0

查看代码,我看不出它为什么会陷入无限循环。我要做的是跟踪 number 的值,看看它是否不会跳过七个案例。
另外,作为一个好习惯,我认为最好将相等 (==) 更改为高级或相等 (>=)。您可能最终会在将来更改增量步骤并忘记更新条件,这也将导致无限循环:)
最后一点,不相关的评论,通常最好不要使用文字常量(如 7)并更喜欢使用声明的常量。这对于代码理解和更新都是最好的。

于 2012-04-23T01:54:59.810 回答