newbie
newbie

Reputation: 221

how to run array using for loop and do while loop

I'm newbie in Java and my problem is the output of my code will loop to infinity. First, I was asked to initialize the number of tickets to sum of number of children and number of adults.

  int noOfChildren = 2;
  int noOfAdults = 5;
  int noOfTicket = noOfChildren + noOfAdults;

Second is to use single dimension array to store travel pass IDs and initialize it to total number of children and number of adults participating in an event. And then use for loop to generate travel pass ID:

 int[] travelID;
 travelID = new int[noOfTicket];

for(int i = 0; i < travelID.length; i++)
        {
            travelID[i] = i + 1;
        }

Then I was asked to print the values of the travel pass IDs using the do/while loop. So what I did is like this:

int i = 0;
        do
        {
            System.out.println("ID " + travelID[i] + ":" + travelID[i] );
        }
        while (i < noOfTicket);

However, as I tried to run the code, the output of the code loops instead of displaying 7 values of ID. Can anyone help me with this? Thanks ahead.

Upvotes: 2

Views: 564

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

You need to increment i inside the do while loop. The for loop has i++. The do while loop needs something like that.

Upvotes: 3

Related Questions